无法在node.js中将服务器连接到客户端

分享于2022年07月17日 connect node.js socket.io 问答
【问题标题】:无法在node.js中将服务器连接到客户端(Cannot connect server to client in node.js)
【发布时间】:2022-01-25 00:18:40
【问题描述】:

我正在尝试使用 socket.io 将我的客户端连接到我的服务器以连接它们。但是它似乎不起作用,因为我没有在终端中获得 socket.id 并且我在本地主机中收到此错误 Cannot GET / 。请帮我修复它。非常感谢!

客户:

App.js:

import "./App.css";
import io from "socket.io-client";

const socket = io.connect("http://localhost:3000");

function App() {
  return 
; } export default App;

package.json:

{
  "name": "client",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@testing-library/jest-dom": "^5.16.1",
    "@testing-library/react": "^12.1.2",
    "@testing-library/user-event": "^13.5.0",
    "react": "^17.0.2",
    "react-dom": "^17.0.2",
    "react-scripts": "5.0.0",
    "socket.io-client": "^4.4.0",
    "web-vitals": "^2.1.2"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

服务器: index.js:

const express = require("express");
const app = express();
const http = require("http");
const cors = require("cors");
const {
    Server
} = require("socket.io");


app.use(cors());

const server = http.createServer(app);

const io = new Server(server, {
    cors: {
        origin: "http://localhost:3000",
        methods: ["GET", "POST"],
    },
});

io.on("connection", (socket) => {
    console.log(`User connected: ${socket.id}`);

    socket.on("disconnect", () => {
        console.log("User Disconnected", socket.id);
    });
})

server.listen(3000, () => {
    console.log("SERVER RUNNING");
});

package.json:

{
    "name": "server",
    "version": "1.0.0",
    "description": "",
    "main": "index.js",
    "scripts": {
        "test": "echo \"Error: no test specified\" && exit 1",
        "start": "nodemon index.js"
    },
    "author": "",
    "license": "ISC",
    "dependencies": {
        "connect": "^3.7.0",
        "cors": "^2.8.5",
        "express": "^4.17.2",
        "nodemon": "^2.0.15",
        "socket.io": "^4.4.0"
    }
}


【解决方案1】:

对于这个例子,socket.io 的工作代码

let express = require('express');    
let app = express();

let server = require('http').createServer(app);
let io = require('socket.io')(server, {
    cors: {
        origin: "*",
        methods: ["GET", "POST"],
        credentials: true
    }
})

  • 我试过了,但是没用...
  • 难道react和socket都在同一个3000端口上工作?
  • 什么意思?
  • 显然你的服务器端和客户端占用了3000端口,导致报错