Created
June 24, 2015 15:05
-
-
Save hhanh00/ddf3bf62294fc420a0de to your computer and use it in GitHub Desktop.
Reverse Proxy for websockets using Express JS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); |
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
Thankyou this saved me a lot of time :)