代理节点请求到新的端口,并像逆向代理一样行事

我需要创build一个代理端口A到端口B请求的应用程序。例如,如果用户在端口3000上连接,他将被路由到(端口3001)端口,因此“原始”应用程序将运行在端口3001上但在客户端(浏览器)用户将把端口3000.不redirect…

http://example.com:3000/foo/bar

一个新的服务器将被创build,监听端口3001,所有的呼叫实际上是端口3000与新的服务器和新的端口运行。 由于端口3000实际上是由我的反向代理应用程序占用? 我应该如何testing它…

有没有办法来testing这个来validation这是否正在工作,例如通过unit testing?

我发现这个模块https://github.com/nodejitsu/node-http-proxy可能会有帮助。

直接从node-http-proxy文档 ,这是相当简单的。 你可以简单地通过向端口3000发送一个HTTP请求来testing它 – 如果你得到和你在端口3001上一样的响应,它就可以工作:

 var http = require('http'), httpProxy = require('http-proxy'); // // Create a proxy server with custom application logic // var proxy = httpProxy.createProxyServer({}); var server = http.createServer(function(req, res) { // You can define here your custom logic to handle the request // and then proxy the request. proxy.web(req, res, { // Your real Node app target: 'http://127.0.0.1:3001' }); }); console.log("proxy listening on port 3000") server.listen(3000); 

我强烈build议你使用mocha这样的项目编写一套集成testing,这样你就可以直接对你的服务器和代理进行testing。 如果两种testing都通过,那么你可以放心,你的代理行为如预期。

使用摩卡和should.js的unit testing看起来像这样:

 var should = require('should'); describe('server', function() { it('should respond', function(done) { // ^ optional synchronous callback request.get({ url: "http://locahost:3000" // ^ Port of your proxy }, function(e, r, body) { if (e) throw new Error(e); body.result.should.equal("It works!"); done(); // call the optional synchronous callback }); }); }); 

然后,您只需运行您的testing(一旦安装了Mocha):

 $ mocha path/to/your/test.js 

您可以通过将以下内容添加到代理请求来validation这是否正常工作(如Remus答案中所述)

 proxy.on('proxyReq', function (proxyReq, req, res, options) { res.setHeader('App-Proxy', 'proxy'); }); 

通过这种方式,您可以validation您的“原始”呼叫是否与新的服务器代理工作,甚至提供创buildUT的能力,此外,您可以使用changeOrigin:true属性…