这是我的代理设置:
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'});
}
});
希望有更优雅的虚拟主机解决方案。
答案 0 :(得分:0)
事实证明这很简单:
server.on('upgrade', vhost('api.*.*', function(req, socket, head) {
proxy.ws(req, socket, head);
}));
vhost
可以围绕upgrade
侦听器,就像它可以用作http请求的中间件一样。