node.js - 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 相同的过程。
解决方案
从 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"
}
});
推荐阅读
- sql-server - 存储过程中的 T-SQL Merge 语句引发错误
- phpstorm - Remote hosts password file PhpStorm linux
- node.js - 如何以数组的原始顺序返回sequelize findAll(array)?
- python - Controlling GPIO in RPI via python 2 input
- python - Animation on top of static plot on plotly
- java - Widget Spinner displays list but selecting result will not show
- python - 检测图像中的文本
- python - 在 QHeaderView 中获取标题部分文本
- swift - Convert [Future
- angular - ngx-datatable date sorting by Year ANGULAR 8