如何门面(代理)websocket 端口

How to facade (proxy) websocket port

我有服务器端渲染 React 应用程序,我在其中代理了对不同端口的所有 http 调用。 http代理请看下面的代码。

import proxy from "express-http-proxy";
const app = express();
const bodyParser = require("body-parser");
const http = require('http');
const  httpProxy = require('http-proxy');
const PORT = process.env.PORT || 3001;
httpProxy.createServer({
    target: 'ws://localhost:4000',
    ws: true
}).listen(PORT); //Throws error since 3000 port is already used by //app.listen.
app.use(
  "/api",
  proxy("http://localhost:4000/", {

    proxyReqOptDecorator(opts) {
      opts.headers["x-forwarded-host"] = "http://localhost:4000/";
      return opts;
    }
  })
);
app.post("/logger", (req, res) => {
  logger.debug(req.body.data);
  res.send({ status: "SUCCESS" });
});

app.listen(PORT, () => {
  logger.debug(`Portal listening on ${PORT}`);
});

这意味着当我进行任何调用时 /api/endpoint 它将重定向到 localhost:4000/endpoint 但在网络中将被视为 http://localhost:3000/endpoint1

我也希望 websockets 具有相同的行为。 我正在使用新的 WebSocket(ws://localhost:3000/endpoint1);它应该重定向到 ws://localhost:4000/endpoint1。 并且应该在网络选项卡中显示为 ws://localhost:3000/endpoint1

使用另一个库 http-proxy-middleware 解决了它

import httpproxy from "http-proxy-middleware";
import proxy from "express-http-proxy";
const app = express();
const bodyParser = require("body-parser");
const PORT = process.env.PORT || 3001;
const wsProxy = httpproxy('/ws', {
    target: 'ws://localhost:4000',
    pathRewrite: {
      '^/ws' : '/',        // rewrite path.
      '^/removepath' : ''               // remove path.
     },
    changeOrigin: true, // for vhosted sites, changes host header to match to target's host
    ws: true, // enable websocket proxy
    logLevel: 'debug'
});

app.use(wsProxy);
app.use(
  "/api",
  proxy("http://localhost:4000/", {

    proxyReqOptDecorator(opts) {
      opts.headers["x-forwarded-host"] = "http://localhost:4000/";
      return opts;
    }
  })
);
app.post("/logger", (req, res) => {
  logger.debug(req.body.data);
  res.send({ status: "SUCCESS" });
});

app.listen(PORT, () => {
  logger.debug(`Portal listening on ${PORT}`);
});