node.js - 在expressjs中使用node-http-proxy时出错

标签 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

我已按要求添加了目标,但仍然出现相同的错误。

最佳答案

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

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

关于node.js - 在expressjs中使用node-http-proxy时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9787660/

相关文章:

angular - 如何修复 [对象 : null prototype] { title: 'product' }

node.js - Node ,当我运行 package.json `bin` `command` 时,给我 `syntax error near unexpected token ` (' `

node.js - 处理断开/注销事件

node.js - 当所需文件不导出任何内容时,require() 会做什么?设置 Mongoose + express 的正确方法是什么?

javascript - 模块化 node.js/socket.io/express 应用程序的最佳方法

google-chrome-devtools - 使用 webpack-dev-server 时,为什么 Chrome 会在每秒请求之前等待?

javascript - 在 Node.js 代理后面使用虚拟主机运行 Apache

javascript - 使用 Node 代理时出错

node.js - nextTick vs setImmediate,直观解释

javascript - 使用 app.post 和 req.body 获取 undefined