使用 node-http-proxy 在同一子域下代理节点服务器和 websocket 服务器
Proxy a node server and websocket server under same subdomain with 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'});
}
});
希望有一个更优雅的类似 vhost 的解决方案。
原来这么简单:
server.on('upgrade', vhost('api.*.*', function(req, socket, head) {
proxy.ws(req, socket, head);
}));
vhost
可以包裹在 upgrade
侦听器周围,就像它可以用作 http 请求的中间件一样。
这是我的代理设置:
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 请求的中间件一样。