使用node-http-proxy代理节点服务器和websocket服务器在相同的子域下

时间:2015-10-19 04:09:43

标签: javascript node.js websocket subdomain node-http-proxy

这是我的代理设置:

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.');
});

我是否需要深入了解vhost处理程序中的req, res对象来路由套接字请求?什么是正确的方法?

更新

不漂亮,但我会尝试一下。

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'});
  }
});

希望有更优雅的虚拟主机解决方案。

1 个答案:

答案 0 :(得分:0)

事实证明这很简单:

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

vhost可以围绕upgrade侦听器,就像它可以用作http请求的中间件一样。