如何使用NextJS转发/代理WebSocket?

tpgth1q7  于 2023-06-22  发布在  其他
关注(0)|答案(1)|浏览(215)

我的app被分成两部分。NextJS前端和独立的Sping Boot GraphQL API后端。
假设NextJS服务器是https://a.com/,Sping Boot 服务器是https://b.com/
如何将https://a.com/graphql的所有请求转发到https://b.com/graphql,包括WebSocket的东西,因为GraphQL使用WebSockets来实现它的 * 订阅 * 功能。
我知道您可以像这样在next.config.js中设置重写

module.exports = {
  async rewrites() {
    return [
      {
        source: '/graphql',
        destination: 'https://b.com/graphql',
      },
    ]
  },
}

但是我不知道这个方法是否也支持WebSockets。

gzjq41n4

gzjq41n41#

使用自己的代理服务器创建并运行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));

相关问题