2

This is my proxy setup:

var express = require('express');
var vhost   = require('vhost');
var proxy   = require('http-proxy').createProxyServer();

var app = express();
var server = http.createServer(app);

// route api subdomain to port 2000
app.use(vhost('api.*.*', function(req, res) {
  proxy.web(req, res, {target: 'http://localhost:2000'});
}));

// I need to get websocket requests to ws://api.example.com proxied port 4000
server.on('upgrade', function(req, socket, head) {
  // proxy.ws seems like the right way to go, but how do I get this under the vhost?
  proxy.ws(req, socket, head);
});

// everything else goes to port 3000
app.get('*', function(req, res) {
  proxy.web(req, res, {target: 'http://localhost:3000'});
});

server.listen(80, function() {
  console.log('Proxy listening on port 80.');
});

Do I need to dive into the req, res objects inside the vhost handler to route the socket request? What is the right approach?

Update

Not pretty, but I'm going to give this a try.

server.on('upgrade', function(req, socket, head) {
  var host = req.headers.host;
  var parts = host.split('.');
  if (parts.length === 3 && parts[0] === 'api') {
    proxy.ws(req, socket, head, {target: {target: 'http://localhost:2000'});
  }
});

Hopeful for a more elegant vhost-like solution.

m59
  • 43,214
  • 14
  • 119
  • 136
  • `Error: connect ECONNREFUSED 127.0.0.1:3000 at Object.exports._errnoException (util.js:874:11) at exports._exceptionWithHostPort (util.js:897:20) at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1063:14)` Have you gotten something similar to that? – Max Oct 19 '15 at 04:22
  • @MaxMastalerz No, I have a server running on port 2000 and 3000. They work great. I just can't figure out the websocket part. – m59 Oct 19 '15 at 04:24
  • @MaxMastalerz I got it figured out in case you're curious! – m59 Oct 19 '15 at 04:57

1 Answers1

0

It turns out to be as simple as this:

server.on('upgrade', vhost('api.*.*', function(req, socket, head) {
  proxy.ws(req, socket, head);
}));

vhost can be wrapped around the upgrade listener just like it can be used as middleware for http requests.

m59
  • 43,214
  • 14
  • 119
  • 136