将node-http-proxy与expressjs一起使用时出错

时间:2012-03-20 13:24:29

标签: node.js express node-http-proxy

我没有得到node-http-proxy的最新版本(虽然这曾经在以前的版本中工作)。 Node.js版本为0.6.12,node-http-proxy版本为0.8.0。 基本上,我有一个服务器在端口10000上监听,另一个监听端口5000.我想代理这个最后一个人所有以/ api开头的请求(在删除这个前缀之后)。

我的代码是:

var express = require("express");
var httpProxy = require('http-proxy');
var cluster = require('cluster');
var fs = require('fs');

// Use http server for local tests
var app = express.createServer();

// Proxy request targeting API
app.all('/api/*',function(req, res){

  // Remove '/api' part from query string
  req.url = '/' + req.url.split('/').slice(2).join('/');

  // Create proxy
  var proxy = new httpProxy.HttpProxy();
  proxy.proxyRequest(req, res, {
    target: {
      host: 'localhost',
      port: 5000
    }
  });
});

// Handle static files
app.use(express.static(__dirname + '/public'));

// Run application
app.listen(10000);

正确地提供了静态文件但是当涉及到代理时,我收到了这个错误:

Error: Both `options` and `options.target` are required.
at new <anonymous> (/Users/luc/Projects/test/www/node_modules/http-proxy/lib/node-http-proxy/http-proxy.js:53:11)
at /Users/luc/Projects/test/www/server.js:15:16
at callbacks (/Users/luc/Projects/test/www/node_modules/express/lib/router/index.js:272:11)
at param (/Users/luc/Projects/test/www/node_modules/express/lib/router/index.js:246:11)
at pass (/Users/luc/Projects/test/www/node_modules/express/lib/router/index.js:253:5)
at Router._dispatch (/Users/luc/Projects/test/www/node_modules/express/lib/router/index.js:280:4)
at Object.handle (/Users/luc/Projects/test/www/node_modules/express/lib/router/index.js:45:10)
at next (/Users/luc/Projects/test/www/node_modules/express/node_modules/connect/lib/http.js:203:15)
at Object.handle (/Users/luc/Projects/test/www/node_modules/express/lib/http.js:83:5)
at next (/Users/luc/Projects/test/www/node_modules/express/node_modules/connect/lib/http.js:203:15)-error-undefined

我已根据要求添加了目标,但仍然存在相同的错误。

2 个答案:

答案 0 :(得分:3)

您需要将选项传递给HttpProxy构造函数,而不是传递给proxyRequest函数。

https://github.com/nodejitsu/node-http-proxy/blob/master/lib/node-http-proxy/http-proxy.js#L51

答案 1 :(得分:0)

另外,您本来可以尝试说var proxy = new httpProxy.RoutingProxy();