首页 > 解决方案 > Socket.io-client 未连接到 socket.io 服务器反应和节点(快递)

问题描述

我尝试使用以下代码连接到 socket.io-client:

客户:

import queryString from 'query-string';
import React, { useEffect, useState } from 'react';
import io from 'socket.io-client';

let socket;

const Chat = ({location}) => {

const [name, setName] = useState("");
const [room, setRoom] = useState("");
const EP = 'http://localhost:5000/';

useEffect(() =>{
    const {name , room} = queryString.parse(location.search);

    socket = io(EP);

    setName(name);
    setRoom(room);

    console.log(socket);
},[EP, location.search])

return(
    <h1>helloooooooooooooo {name} welcome to {room}</h1>
)
}

export default Chat;

服务器:

const express = require('express');
const socketio = require('socket.io');
const http = require('http');
const router = require('./router/router');

const PORT = process.env.PORT ||5050;

const app = express();
const server = http.createServer(app);
const io = socketio(server);




//socket.io

io.on('connection', socket => {
console.log("we have a new user!!!!!!!!!");

socket.on('disconnect', () =>{
    console.log('User had left!');
})
})

// io.on('connection', socket => { 
//     console.log("we have a new user!!!!!!!!");

//     socket.on("disconnect", () => console.log("user is left"))        
//  });

app.use(router);

server.listen(PORT, () => console.log(`Server has started on ${PORT}`));

我没有从该服务器套接字获取连接或断开控制台日志。我遵循与 socke.io doc 相同的过程。

来自浏览器的控制台消息,它显示断开连接的真和连接的假并且没有 id

标签: node.jsreactjsexpresssocket.io

解决方案


从 Socket.IO v3 开始,您需要显式启用跨域资源共享 (CORS)。 https://socket.io/docs/v3/handling-cors/

// server-side
const io = require("socket.io")(httpServer, {
  cors: {
    origin: "https://example.com",
    methods: ["GET", "POST"],
    allowedHeaders: ["my-custom-header"],
    credentials: true
  }
});

// client-side
const io = require("socket.io-client");
const socket = io("https://api.example.com", {
  withCredentials: true,
  extraHeaders: {
    "my-custom-header": "abcd"
  }
});

推荐阅读