如何在Node中为websocket做代理

时间:2018-05-24 04:45:19

标签: node.js npm websocket middleware

在Node中,我可以通过以下方式执行http代理:

https://localhost:443 -> http://localhost:8100

使用以下代码:

var express = require('express');
var app = express();
var https = require('https');
var httpProxy = require('http-proxy');
...
app.use(function (req, res, next) {
    httpProxy.createServer({
        target: {
            host: 'localhost',
            port: 8100,
        }
    }).web(req, res);
});
...
https.createServer(sslOptions, app).listen(443, function(){
    console.log('App running on port: 443');
});

但我还需要通过以下方式对Web套接字进行类似的重定向:

wss://localhost:8107 -> ws://localhost:8100

您对我如何实现这一目标有任何想法吗?

谢谢!

1 个答案:

答案 0 :(得分:0)

http-proxy模块supports websockets

只需:

httpProxy.createServer({
  target: 'ws://localhost:8100',
  ws: true
}).listen(8107);