如何构建(代理)WebSocket端口

时间:2019-03-04 15:14:36

标签: javascript node.js reactjs express serverside-javascript

我有服务器端渲染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

1 个答案:

答案 0 :(得分:1)

通过使用另一个库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}`);
});