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

React+Firebase环境下Socket.io连接被拒绝问题求助

排查Socket.io连接拒绝与Axios网络错误的步骤

1. 确认后端服务状态

  • 检查运行在localhost:3001的后端服务是否已启动,查看终端是否有服务正常运行的日志。若未启动,执行对应启动命令(如npm start或node server.js)。
  • 验证端口3001是否被占用:Mac/Linux终端执行lsof -i :3001,Windows执行netstat -ano | findstr :3001,若端口被其他进程占用,可终止该进程或修改后端服务端口。

2. 核对后端路由与Socket.io配置

  • 确认后端存在GET /api/room路由,且路由逻辑无异常导致服务崩溃。
  • 检查Socket.io初始化代码,确保其正确绑定到HTTP服务器实例,示例如下:
    const express = require('express');
    const http = require('http');
    const { Server } = require('socket.io');
    
    const app = express();
    const server = http.createServer(app);
    const io = new Server(server, {
      cors: {
        origin: "http://localhost:3000", // 允许React前端跨域请求
        methods: ["GET", "POST"]
      }
    });
    

3. 检查跨域(CORS)配置

  • React默认运行在3000端口,后端必须配置CORS允许来自http://localhost:3000的请求。使用cors中间件的示例配置:
    const cors = require('cors');
    app.use(cors({
      origin: 'http://localhost:3000',
      credentials: true // 若需携带Cookie或认证信息则开启
    }));
    

4. 验证前端请求配置

  • 检查ChatService.js中Axios的baseURL与请求路径是否正确,避免拼写错误:
    import axios from 'axios';
    
    const chatApi = axios.create({
      baseURL: 'http://localhost:3001',
    });
    
    export const getRoom = async () => {
      return await chatApi.get('/api/room');
    };
    
  • 检查ChatRoom.js中Socket.io的连接地址是否指向后端3001端口,可显式指定传输方式优化连接:
    import { io } from 'socket.io-client';
    
    const socket = io('http://localhost:3001', {
      transports: ['websocket', 'polling']
    });
    

5. 排查防火墙或代理问题

  • 临时关闭本地防火墙,测试是否能正常连接3001端口。
  • 若前端使用代理(如package.json中的proxy字段),确保配置正确指向http://localhost:3001,此时前端请求可省略域名直接写/api/room:
    {
      "proxy": "http://localhost:3001"
    }
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 22:29:55