基于路径的代理与http-proxy nodejs

时间:2014-04-02 10:20:14

标签: node.js node-http-proxy

我想要一个基于路径的路由代理。 但是我的代码不能正常工作

var httpProxy = require('http-proxy')

var proxy = httpProxy.createProxy();

var options = {
'example.com/app1': 'http://localhost:4444',
'example.com/app2': 'http://localhost:3333'
}

require('http').createServer(function(req, res) {
proxy.web(req, res, {
    target: options[req.headers.host]
},function(error) {

});
}).listen(80);

问题是怎么回事?

感谢您的帮助

2 个答案:

答案 0 :(得分:2)

您可能想尝试express-http-proxy,这样可以在快速路线上安装代理:

app.use('/app1/', proxy('http://localhost:4444', {
    forwardPath: function(req, res){
      return url.parse(req.url).path.replace(/\/app1/,'/');
    }
  })
);

即使您要求使用node.js解决方案,我也不能真正建议使用此路由(没有双关语)。 对于使用此特定用例进行了更多测试的内容,您可能会感觉更好 - 比如nginx:

location /app1/ {
  proxy_pass http://localhost:4444;
}

答案 1 :(得分:1)

最新版本的http-proxy放弃了可代理功能。见https://github.com/nodejitsu/node-http-proxy/blob/master/UPGRADING.md 版本0.8.x可以执行基于路径的路由。对于当前的http-proxy,中间件可以为其执行代理表(https://github.com/dominictarr/proxy-by-url