如何立面(代理)Websocket端口



我有服务器端渲染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/端点时,它将重定向到localhost:4000/endpoint,但在网络中将看到为http://localhost:3000/endpoint1

我也希望与Websocket相同。我正在使用新的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}`);
});

最新更新