这是我的代理设置:

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


希望有一个更优雅的类似于vhost的解决方案。

最佳答案

事实如此简单:

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


vhost可以包裹在upgrade侦听器周围,就像可以用作http请求的中间件一样。

10-06 11:37