【发布时间】:2019-07-25 22:27:30
【问题描述】:
我有服务器端渲染反应应用程序,其中我将所有 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
【问题讨论】:
-
感谢院长的评论。在你给出这个之后,我已经使用了 note-http-proxy。我可以看到它正在成功代理。但问题是我想在我的快递正在监听的同一个端口上代理。我不能有两个不同的端口。我想在同一个端口同时监听 http 和 websockets。
-
这看起来像是架构问题。您可以使用 Apache 和 Nginx 等 Web 服务器在同一端口上运行多个应用程序。我快速搜索了一下,发现dietjs.com 可能会有所帮助。我敢肯定 node-http-proxy 也支持这个。
-
@DeanMeehan 我刚刚修改了我的代码并粘贴了。你能建议如何合并 http-proxy 和 express-http-proxy
标签: javascript node.js reactjs express serverside-javascript