Summary
In this post I'll show how to create a simple reverse proxy server in Node.js.
Environmentals
The scenario here is front-ending an app server (in this case Genesys Mobility Services (GMS) with a proxy to only forward application-specific REST API requests to GMS over HTTPS. The proxy also acts as a general web server as well - also over HTTPS.
Code
var path = require('path');
var fs = require('fs');
var gms = 'https://svr2:3443';
var express = require('express');
var app = express();
var privateKey = fs.readFileSync('./key.pem');
var certificate = fs.readFileSync('./cert.pem');
var credentials = {key: privateKey, cert: certificate};
var https = require('https');
var httpsServer = https.createServer(credentials, app);
var httpProxy = require('http-proxy');
var proxy = httpProxy.createProxyServer({
secure : false,
target : gms
});
httpsServer.on('upgrade', function (req, socket, head) {
proxy.ws(req, socket, head);
});
proxy.on('error', function (err, req, res) {
console.log(err);
try {
res.writeHead(500, {
'Content-Type': 'text/plain'
});
res.end('Error: ' + err.message);
} catch(err) {
console.log(err);
}
});
app.use(express.static(path.join(__dirname, 'public')));
app.all("/genesys/*", function(req, res) {
proxy.web(req, res);
});
httpsServer.listen(8443);
Lines 1-11: Set up a HTTPS server with Express. The proxy target is specified in Line 3.Lines 13-17: Set up the Proxy. I'm using a self-signed certificate on Svr 2, so 'secure' is set to false to support that.
Lines 19-21: Configure the HTTPS server use the Proxy to proxy websockets.
Line 35: Serve up static content (HTML, CSS, Javascript) from the 'public' directory for general requests to this server.
Lines 37-39: Proxy any requests that are specifically to the GMS REST API, both HTTPS and WSS traffic.
Source: https://github.com/joeywhelan/Revproxy/
Copyright ©1993-2024 Joey E Whelan, All rights reserved.
