NestJS/React环境下Socket.io 404错误排查求助
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.tssetup- React client connection code
That will help narrow down the exact issue.
内容的提问来源于stack exchange,提问作者acatina

