Search code examples
javascriptnode.jsexpressreverse-proxynode-http-proxy

proxy node request to new port and act like reverse proxy


I need to create an application that proxies a request from port A to Port B. For instance if a user connects on port 3000 he will be routed (under the hood) to port 3001, therefore the "original" application will run on port 3001 but in the client (browser) the user will put port 3000. Not redirect...

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

A new server will be created which listens to port 3001 and all the call are actually to port 3000 running with the new server and new port. Since port 3000 is actually occupied,by my reverse proxy app? how should I test it...

Is there a way to test this to verify that this is working,e.g. by unit testing?

I've found this module https://github.com/nodejitsu/node-http-proxy which might be able to help.


Solution

  • Straight from the node-http-proxy docs, this is quite simple. You can test it simply by making an HTTP request to port 3000 -- if you get the same response as you do on port 3001, it's working:

    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);
    

    I highly recommend you write a suite of integration tests using some thing like for your project as well - in this way, you can run your tests both against your server directly and against your proxy. If tests pass against both, then you can be assured your proxy is behaving as expected.

    A unit test using and would look something like this:

    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
            });
        });
    });
    

    You then simply run your test (once Mocha is installed):

    $ mocha path/to/your/test.js