reactjs 我如何让socket.io通过react和vite使用express后端代理工作?

nhaq1z21  于 2023-05-28  发布在  React
关注(0)|答案(1)|浏览(187)

我无法让socket.io通过react+vite(PORT 5173),express(PORT 5002)代理工作。我从当前配置收到一个ERROR: server error。我的后端没有收到任何连接尝试。
我希望代理使用我的后端进行套接字连接。(我想我正在尝试代理命名空间,例如。const socket = io("/api"), to change from /api to http://localhost:5002)
以下是我的设置中的相关部分。我的react / client组件:

import { io } from 'socket.io-client';

export const socket = io('/ws', {
  autoConnect: false,
  withCredentials: true,
});

我的vite.config.ts代码:

import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';

// https://vitejs.dev/config/
export default defineConfig({
  server: {
    host: '0.0.0.0',
    proxy: {
      '/ws': {
        target: 'http://localhost:5002',
        changeOrigin: true,
        secure: false,
        ws: true,
        rewrite: path => path.replace(/^\/ws/, ''),
      },
    }
  },
  plugins: [react()],
});

我的Express服务器端代码:

import express, from 'express';
import { createServer } from 'http';
import { Server } from 'socket.io';

const app = express();
const httpServer = createServer(app);

app.use(
  cors({
    credentials: true,
    origin: process.env.CLIENT_URL,
  })
);

const port = 5002;

const io = new Server(httpServer, {
   cors: {
     origin: process.env.CLIENT_URL,
     credentials: true,
   },
});

io.on('connection', async (socket) => {...})

httpServer.listen(port, () => {
  console.log(`Server is listening on Port: ${port}`);
});

每当我将vite config和react组件中的路径从'ws'更改为'socket'时,错误就会发生变化,我会得到一个Error: xhr poll error。当这种情况发生时,我的后端会收到一个GET /.io/?EIO=4&transport=polling&t=OXLHE7k 404 1.653 ms - 5
当我从vite中删除代理并在react组件中使用完整的url时,它工作正常,一切都按预期运行,没有错误,

export const socket = io('http://localhost:5002', {
  autoConnect: false,
  withCredentials: true,
});

但是我现在想在开发中使用代理,这是我的目标,最终我将在生产中使用nginx代理。

guykilcj

guykilcj1#

解决方案是使用const socket = io(options)https://socket.io/docs/v4/client-initialization/#from-the-same-domain
然后vite配置将是:

export default defineConfig({
  server: {
    host: '0.0.0.0',
    proxy: {
      '/socket.io/': {
        target: 'http://localhost:5002',
        changeOrigin: true,
        secure: false,
        ws: true,
      },
    }
  },
  plugins: [react()],
});

相关问题