node-http-proxy websocket代理和中间件

我想反向代理使用websockets的现有应用程序,但使用应用程序中间件在应用程序前面实现授权层。

节点http代理广告这两个function,但我似乎无法结合起来。

反向代理websockets工作正常:

var httpProxy = require('http-proxy'); httpProxy.createProxyServer({ target: 'http://127.0.0.1:8888', // where do we want to proxy to? ws : true // proxy websockets as well }).listen(3000); 

当我看一下中间件的例子 ,他们似乎都使用连接的服务器,并在那一点上的websocket支持似乎消失。 例如。

 var httpProxy = require('http-proxy'), connect = require('connect'); var proxy = httpProxy.createProxyServer({ target: 'http://localhost:8888', ws: true }); connect.createServer( connect.compress({ // Pass to connect.compress() the options // that you need, just for show the example // we use threshold to 1 threshold: 1 }), function (req, res) { proxy.web(req, res); } ).listen(3000); 

这是一个已知的限制,还是有其他方式来结合websocket反向代理和中间件?

您需要从http服务器的upgrade事件中调用proxy.ws()

 // Listen to the `upgrade` event and proxy the // WebSocket requests as well. // proxyServer.on('upgrade', function (req, socket, head) { proxy.ws(req, socket, head); }); 

请参阅: https : //github.com/nodejitsu/node-http-proxy#proxying-websockets

您可以使用http-proxy-middleware作为中间件。 它将代理http请求和websocket:

 var http = require('http'); var connect = require('connect'); var proxyMiddleware = require('http-proxy-middleware'); var proxy = proxyMiddleware('http://localhost:8888', { changeOrigin: true, // for vhosted sites ws: true }); var app = connect(); app.use(proxy); // <- add the proxy to connect var server = http.createServer(app).listen(3000); 

检出文档以获取更多configuration选项:

https://www.npmjs.com/package/http-proxy-middleware