gpt4 book ai didi

javascript - 如何门面(代理)websocket 端口

转载 作者:行者123 更新时间:2023-11-30 19:45:26 24 4
gpt4 key购买 nike

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

关于javascript - 如何门面(代理)websocket 端口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54986126/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com