the*_*ker 8 javascript websocket node.js reactjs next.js
我的应用程序分为两部分。NextJS 前端和单独的 Spring Boot GraphQL API 后端。
假设 NextJS 服务器是https://a.com/,Spring Boot 服务器是https://b.com/
如何将https://a.com/graphql的所有请求转发到https://b.com/graphql包括 WebSocket 内容,因为 GraphQL 使用 WebSocket 来实现其订阅功能。
next.config.js我知道你可以像这样设置重写
module.exports = {
async rewrites() {
return [
{
source: '/graphql',
destination: 'https://b.com/graphql',
},
]
},
}
Run Code Online (Sandbox Code Playgroud)
但我不知道这个方法是否也支持 WebSockets。
小智 1
使用您自己的代理服务器创建并运行 nextjs。
import * as dotenv from "dotenv";
dotenv.config();
import express from "express";
import { createProxyMiddleware } from "http-proxy-middleware";
import next from "next";
import { Environment } from "./src/utils/environment";
const { port, backendHost } = Environment;
const backendPort = 5000;
const target = `http://${backendHost}:${backendPort}`;
const app = next({ dev: true, hostname: "localhost", port });
const handle = app.getRequestHandler();
app
.prepare()
.then(() => {
const server = express();
server.use(
"/graphql",
createProxyMiddleware({
target,
pathRewrite: { "^/graphql": "/graphql" },
secure: false,
changeOrigin: true,
logLevel: "debug",
ws: true,
})
);
server.use(
"/api",
createProxyMiddleware({
target,
pathRewrite: { "^/api": "" },
secure: false,
changeOrigin: true,
logLevel: "debug",
ws: false,
})
);
server.all(/^\/_next\/webpack-hmr(\/.*)?/, async (req, res) => {
handle(req, res);
});
server.all("*", (req, res) => handle(req, res));
server.listen(port, () => console.log(`> Ready on http://localhost:${port}`));
})
.catch((err) => console.log("Error:::::", err));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1231 次 |
| 最近记录: |