没有使用快递代理路线的回应
我已经用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没有回应,也许有回应,但我没有在浏览器中出现。
更简单的pipe
和request
包装
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) }); });
- EC2托pipe了Node.js应用程序 – 无法远程连接到端口
- 使用来自node.js的凭证反向代理login
- 适用于使用代理的客户端的socket.io flash(和其他)回退的正确设置
- 在一个端口上使用单个应用程序的节点应用程序使用代理服务器(如node-http-proxy)有什么意义?
- 我可以在TypeScript中使用自定义模块parsing函数(如“proxyquire”)来代替require()吗?
- Nodejs请求代理stream(mjpeg)连接永远不会结束
- 使用nodejs代理ac#HttpWebRequest
- 创build一个通过客户端计算机路由的代理
- Nodejs请求“代理”选项不是通过定义的主机的路由请求