代理节点请求到新端口并像反向代理一样

17 javascript reverse-proxy node.js express node-http-proxy

我需要创建一个代理从端口A到端口B的请求的应用程序.例如,如果用户在端口3000上连接,他将被路由(在引擎盖下)到端口3001,因此"原始"应用程序将在端口3001上运行但在客户端(浏览器)中,用户将输入端口3000.不重定向...

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

将创建一个侦听端口3001的新服务器,所有呼叫实际上都是使用新服务器和新端口运行的端口3000.由于端口3000实际被占用,我的反向代理应用程序?我该怎么测试呢......

有没有办法测试这个以验证这是否有效,例如通过单元测试?

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

bra*_*ipt 8

直接来自node-http-proxy文档,这很简单.您可以通过向端口3000发出HTTP请求来测试它 - 如果您获得与端口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);
Run Code Online (Sandbox Code Playgroud)

我强烈建议你使用像这样的东西为你的项目编写一套集成测试- 通过这种方式,你可以直接针对你的服务器和你的代理运行测试.如果测试通过两者,那么您可以放心,您的代理行为符合预期.

使用单元测试看起来像这样:

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
        });
    });
});
Run Code Online (Sandbox Code Playgroud)

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

$ mocha path/to/your/test.js
Run Code Online (Sandbox Code Playgroud)

  • 谢谢,但这个测试不足以验证这是否正常... :),我将呼叫路由到其他端口的地方在哪里?创建服务器...这是我面临的问题 (2认同)