没有使用快递代理路线的回应

我已经用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 }); }); 

问题是,雅虎api没有回应,也许有回应,但我没有在浏览器中出现。

更简单的piperequest包装

 var request = require('request'); app.use('/api', function(req, res) { var url = apiUrl + req.url; req.pipe(request(url)).pipe(res); }); 

它将整个请求pipe理到API,并将响应传送回请求者。 这也处理POST / PUT / DELETE和所有其他请求\ o /

如果你也关心查询string,你也应该pipe它

 req.pipe(request({ qs:req.query, uri: url })).pipe(res); 

在testing时,也许你的代码是不同的,但是我使用下面的代码来查询与你的代码示例中相同的URL:

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 }); 

也许我用错误的方式使用http代理。 使用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) }); });