【问题标题】:node-http-proxy websocket proxying & middlewarenode-http-proxy websocket 代理和中间件
【发布时间】:2014-04-19 06:42:30
【问题描述】:

我想反向代理一个使用 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 反向代理和中间件?

【问题讨论】:

  • 你弄明白了吗?

标签: node.js proxy websocket


【解决方案1】:

您可以使用http-proxy-middleware 作为中间件。 它将代理 http-requests 和 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

【讨论】:

  • 考虑我正在代理一个不支持 gzip 压缩的闪亮服务器。我如何在此处使用 http-proxy-middleware 为其启用压缩?我有一个类似的用例,就像你编码的一样
【解决方案2】:

您需要在 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-09-14
    • 1970-01-01
    • 1970-01-01
    • 2014-09-12
    • 1970-01-01
    • 2014-03-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多