You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

NestJS/React环境下Socket.io 404错误排查求助

Troubleshooting Socket.io 404 Errors in NestJS + React Setup

Here are the most common fixes for the 404 error you're seeing when connecting your React client to a NestJS WebSocket gateway:

1. Verify Gateway Configuration

Ensure your @WebSocketGateway() decorator has the correct settings. If your NestJS app runs on port 3001 (matching your error URL), explicitly set the port and CORS options to allow your React client (typically on port 3000):

import { WebSocketGateway } from '@nestjs/websockets';

@WebSocketGateway({
  port: 3001,
  cors: {
    origin: 'http://localhost:3000',
    credentials: true,
  },
})
export class ChatGateway {}

2. Check Root Module Imports

Make sure your gateway's module is imported into your root AppModule. If you created the gateway with the Nest CLI, this should be done automatically, but double-check:

import { Module } from '@nestjs/common';
import { ChatGateway } from './chat.gateway';

@Module({
  providers: [ChatGateway],
})
export class AppModule {}

3. Fix Client-Side Connection URL

Your React client must connect directly to the NestJS server's port, not the React dev server. Update your client code to point to http://localhost:3001:

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

const socket = io('http://localhost:3001', {
  withCredentials: true,
});

4. Match Socket.io Versions

Mismatched versions between the server (@nestjs/platform-socket.io) and client (socket.io-client) often cause connection issues. Run these commands to ensure both are on the same major version (e.g., v4.x):

# Server side
npm install @nestjs/platform-socket.io@latest
# Client side
npm install socket.io-client@latest

5. Validate CORS Setup in Main App

If you're setting CORS at the app level instead of the gateway, ensure it's configured to allow your client origin:

// main.ts
async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.enableCors({
    origin: 'http://localhost:3000',
    credentials: true,
  });
  await app.listen(3001);
}
bootstrap();

If none of these fixes work, share snippets of your:

  • NestJS gateway code
  • main.ts setup
  • React client connection code

That will help narrow down the exact issue.

内容的提问来源于stack exchange,提问作者acatina

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 22:20:10