![](/img/trans.png)
[英]Node js - Socket.io-client is not connecting to socket.io server
[英]Socket.io-client is not connecting to socket.io server react and node(express)
我嘗試使用以下代碼連接到 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 文檔相同的過程。
由於 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"
}
});
在客戶端,在 useEffect 內部,而不是
socket = io(EP);
對此
socket = io.connect(EP , {
"force new connection" : true,
"reconnectionAttempts": "Infinity",
"timeout" : 10000,
"transports" : ["websocket"],
withCredentials:true,
extraHeaders:{
"my-custom-header": "abcd"
}
});
在瀏覽器中,WebSocket object 不支持附加標頭。 如果您想添加一些標頭作為某些身份驗證機制的一部分,您可以使用transportOptions
屬性。 請注意,在這種情況下,標頭不會在 WebSocket 升級請求中發送。
// WILL NOT WORK in the browser
const socket = new Socket('http://localhost', {
extraHeaders: {
'X-Custom-Header-For-My-Project': 'will not be sent'
}
});
// WILL NOT WORK
const socket = new Socket('http://localhost', {
transports: ['websocket'], // polling is disabled
transportOptions: {
polling: {
extraHeaders: {
'X-Custom-Header-For-My-Project': 'will not be sent'
}
}
}
});
// WILL WORK
const socket = new Socket('http://localhost', {
transports: ['polling', 'websocket'],
transportOptions: {
polling: {
extraHeaders: {
'X-Custom-Header-For-My-Project': 'will be used'
}
}
}
});
信用: Engine.IO 客戶端
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.