我用nodejs,express和htt-proxy编写了一个小代理。它适用于提供本地文件,但在代理外部api时失败:
var express = require('express'),
app = express.createServer(),
httpProxy = require('http-proxy');
app.use(express.bodyParser());
app.listen(process.env.PORT || 1235);
var proxy = new httpProxy.RoutingProxy();
app.get('/', function(req, res) {
res.sendfile(__dirname + '/index.html');
});
app.get('/js/*', function(req, res) {
res.sendfile(__dirname + req.url);
});
app.get('/css/*', function(req, res) {
res.sendfile(__dirname + req.url);
});
app.all('/*', function(req, res) {
req.url = 'v1/public/yql?q=show%20tables&format=json&callback=';
proxy.proxyRequest(req, res, {
host: 'query.yahooapis.com', //yahoo is just an example to verify its not the apis fault
port: 8080
});
});
问题是yahoo api没有回复,也许有回复但我没有在浏览器中出现。
答案 0 :(得分:103)
使用pipe
和request
- 包
var request = require('request');
app.use('/api', function(req, res) {
var url = apiUrl + req.url;
req.pipe(request(url)).pipe(res);
});
它将整个请求传递给API,并将响应传递回请求者。这也处理POST / PUT / DELETE和所有其他请求\ o /
如果你也关心查询字符串,你也应该管它
req.pipe(request({ qs:req.query, uri: url })).pipe(res);
答案 1 :(得分:7)
在您测试时,您的代码可能会有所不同,但我使用以下代码查询代码示例中的相同网址:
http://query.yahooapis.com:8080/v1/public/yql?q=show%20tables&format=json&callback=
我一无所获。我的猜测是你要将端口更改为80(从8080开始) - 当我改变它时它会起作用:
http://query.yahooapis.com:80/v1/public/yql?q=show%20tables&format=json&callback=
这意味着它应该是:
proxy.proxyRequest(req, res, {
host: 'query.yahooapis.com', //yahoo is just an example to verify its not the apis fault
port: 80
});
答案 2 :(得分:4)
也许我以错误的方式使用http-proxy。使用restler做我想要的:
var express = require('express'),
app = express.createServer(),
restler = require('restler');
app.use(express.bodyParser());
app.listen( 1234);
app.get('/', function(req, res) {
console.log(__dirname + '/index.html')
res.sendfile(__dirname + '/index.html');
});
app.get('/js/*', function(req, res) {
res.sendfile(__dirname + req.url);
});
app.get('/css/*', function(req, res) {
res.sendfile(__dirname + req.url);
});
app.all('/*', function(req, res) {
restler.get('http://myUrl.com:80/app_test.php/api' + req.url, {
}).on('complete', function (data) {
console.log(data)
res.json(data)
});
});
答案 3 :(得分:0)
我最终使用了http-proxy-middleware。
代码看起来像这样:
var express = require("express");
var proxy = require("http-proxy-middleware");
const theProxy = proxy({
target: "query.yahooapis.com",
changeOrigin: true,
});
app.use("/", theProxy);
app.listen(process.env.PORT || 3002);
答案 4 :(得分:0)
这就是我已经使用了一段时间了。可以处理JSON和二进制请求。
app.use('/api', (req, res, next) => {
const redirectUrl = config.api_server + req.url.slice(1);
const redirectedRequest = request({
url: redirectUrl,
method: req.method,
body: req.readable ? undefined : req.body,
json: req.readable ? false : true,
qs: req.query,
// Pass redirect back to the browser
followRedirect: false
});
if (req.readable) {
// Handles all the streamable data (e.g. image uploads)
req.pipe(redirectedRequest).pipe(res);
} else {
// Handles everything else
redirectedRequest.pipe(res);
}
});