nodejs reverse proxy code example
Example 1: reverse proxy using expressjs
var express = require('express');
var app = express();
var httpProxy = require('http-proxy');
var apiProxy = httpProxy.createProxyServer();
var serverOne = 'http://localhost:3001',
ServerTwo = 'http://localhost:3002',
ServerThree = 'http://localhost:3002';
app.all("/app1/*", function(req, res) {
console.log('redirecting to Server1');
apiProxy.web(req, res, {target: serverOne});
});
app.all("/app2/*", function(req, res) {
console.log('redirecting to Server2');
apiProxy.web(req, res, {target: ServerTwo});
});
app.all("/app2/*", function(req, res) {
console.log('redirecting to Server3');
apiProxy.web(req, res, {target: ServerThree});
});
app.listen(3000);
Example 2: how to make a proxy server node.js
var fs = require('fs');
var http = require('http'),
var https = require('https'),
var httpProxy = require('http-proxy');
isHttps = true;
var options = {
ssl: {
key: fs.readFileSync('valid-key.pem'),
cert: fs.readFileSync('valid-cert.pem')
}
};
proxyServer = proxy.createProxyServer({target:'http://127.0.0.1:9000'});
proxyServer.listen(8000);
if (isHttps){
server = https.createServer(options.ssl, function(req, res) {
console.log(“https request”);
proxyServer.web(req, res, { target: req.url });
proxyServer.on('error', function(e) {
console.log("Error in proxy call");
});
proxyServer.listen(443);
});
}else{
server = http.createServer(function (req, res) {
console.log(req.url);
proxyServer.web(req, res, { target: req.url });
proxyServer.on('error', function(e) {
console.log("Error in proxy call");
});
});
}
server.listen(9000);