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

bnl4lu3b  于 2023-05-28  发布在  Node.js
关注(0)|答案(1)|浏览(188)

我正在尝试使用www.example.com连接我的客户端和服务器socket.io。然而,它似乎不工作,因为我没有得到套接字.id在我的终端,我得到这个错误**无法获得/**在我的本地主机.请帮我修理一下。谢谢你!
客户:
App.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"
    ]
  }
}

server: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"
    }
}
btxsgosb

btxsgosb1#

对于此示例,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
    }
})

相关问题