node-http-proxy websocket proxing&中间件

时间:2014-03-14 05:46:22

标签: node.js proxy websocket

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

node-http-proxy宣传这两个功能,但我似乎无法将它们结合起来。

反向代理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);

当我看一下middleware examples时,他们似乎都使用了连接服务器,那时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反向代理和中间件?

2 个答案:

答案 0 :(得分:0)

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

// 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

答案 1 :(得分:0)

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

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

查看文档以获取更多配置选项:

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