Adam K Dean Adam K Dean - 1 year ago 91
Javascript Question

Node.js - How would I forward HTTP traffic (reverse proxy)?

I need what is essentially a reverse proxy but I need it in Node.js as I will have to put in some custom functionality.

The

gateway
will be the only visible service, and it needs to forward traffic on to an internal network of services. A simple 302 isn't going to work here.

How can I realistically achieve this with Node.js given the asynchronous nature of it?

Are there any well known libraries used for this?

enter image description here

Answer Source

I've managed this using node-http-proxy, where http://first.test/ and http://second.test/ are the hostnames.

var http = require('http'),
    httpProxy = require('http-proxy');

var proxy = httpProxy.createProxyServer({});

// reverse proxy server
http.createServer(function (req, res) {
    var target = '';

    if (req.headers.host.match(/first.test/)) {
        target = 'http://127.0.0.1:8001';
    } else if (req.headers.host.match(/second.test/)) {
        target = 'http://127.0.0.1:8002';
    }

    console.log(req.headers.host, '->', target);
    proxy.web(req, res, { target: target });
}).listen(8000);

// test server 1
http.createServer(function(req, res) {
    res.writeHead(200, { 'Content-Type': 'text/plain' });
    res.write('8001\n');
    res.write(JSON.stringify(req.headers, true, 2));
    res.end();
}).listen(8001);

// test server 2
http.createServer(function(req, res) {
    res.writeHead(200, { 'Content-Type': 'text/plain' });
    res.write('8002\n');
    res.write(JSON.stringify(req.headers, true, 2));
    res.end();
}).listen(8002);