Reputation: 7475
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?
Upvotes: 4
Views: 3625
Reputation: 276
For a simple reverse proxy that uses the reactor pattern (like node), I would check out nginx. But, you mentioned you wanted to add in some custom functionality using node, so is that a realistic goal? Absolutely! Here are some things to think about when you are designing your reverse proxy:
Good luck on your reverse proxy endeavors! I will update this if anything else occurs to me.
Upvotes: 2
Reputation: 7475
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);
Upvotes: 3
Reputation: 11245
With pure core module (may be a bit ugly, but efficient):
var http = require('http');
http.createServer(function (request, response) {
if (request.headers.host === 'api.test') {
// request data from 172.17.0.1:80
} else if (request.headers.host === 'test') {
// request data from 172.17.0.2:80
} else {
// Do something else
}
}).listen(80);
If you don't like this example, you can try: https://www.npmjs.org/package/turtle.io
Upvotes: 1