Skip to content

Instantly share code, notes, and snippets.

@hhanh00
Created June 24, 2015 15:05
Show Gist options
  • Save hhanh00/ddf3bf62294fc420a0de to your computer and use it in GitHub Desktop.
Save hhanh00/ddf3bf62294fc420a0de to your computer and use it in GitHub Desktop.
Reverse Proxy for websockets using Express JS
var http = require('http'),
httpProxy = require('http-proxy'),
express = require('express');
// create a server
var app = express();
var proxy = httpProxy.createProxyServer({ target: 'http://localhost:8080', ws: true });
var server = require('http').createServer(app);
// proxy HTTP GET / POST
app.get('/chat/*', function(req, res) {
console.log("proxying GET request", req.url);
proxy.web(req, res, {});
});
app.post('/chat/*', function(req, res) {
console.log("proxying POST request", req.url);
proxy.web(req, res, {});
});
// Proxy websockets
server.on('upgrade', function (req, socket, head) {
console.log("proxying upgrade request", req.url);
proxy.ws(req, socket, head);
});
// serve static content
app.use('/', express.static(__dirname + "/public"));
server.listen(9000);
@thehappycheese
Copy link

Thankyou this saved me a lot of time :)

@pct-cclausen
Copy link

Line 7 should include some minimal error handling or there will be trouble when the target server is temporarily not available

var proxy = httpProxy.createProxyServer({ target: 'http://localhost:8080', ws: true });
.on("error", (e) => {
            console.log(e);
        });

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment