繁体   English   中英

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

[英]Cannot connect server to client in node.js

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

客户:

应用程序.js:

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

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

function App() {
  return <div className="App"></div>;
}

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"
    }
}

对于这个例子,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
    }
})

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM