我是react.js的新手,我用react.js和socket.io开发了实时聊天应用程序。
由于某些原因,我无法连接到客户端上的套接字!有人能帮忙吗。
客户端文件
import React, { useState, useEffect } from 'react';
import queryString from 'query-string';
import io from 'socket.io-client';
let socket;
const Chat = ({ location }) => {
const [name, setName] = useState('');
const [room, setRoom] = useState('');
const ENDPOINT = 'http://localhost:5000';
useEffect(() => {
const { name, room } = queryString.parse(location.search);
socket = io(ENDPOINT);
setName(name);
setRoom(room);
console.log(socket);
});
return (
<>
<h2>Chat</h2>
<h3>Check </h3>
</>
);
}
export default Chat;
服务器文件
const express = require('express');
const socketio = require('socket.io');
const http = require('http');
const PORT = process.env.PORT || 5000;
const router = require('./router');
const app = express();
const server = http.createServer(app);
const io = socketio(server);
io.on('connect', (socket) => {
console.log('we have a new connection!!!');
socket.on('disconnect', () => {
console.log('User had left!!');
});
});
app.use(router);
server.listen(PORT, () => console.log(`Server has started on port ${PORT}`));
错误
:false
发布于 2021-09-14 09:49:15
即使在本地主机上,您也需要配置CORS,以防web应用程序和服务器无法从同一端口服务。
修改后的socket.io初始化将是
const io = socketio(server, {
cors: {
origin: "http://localhost:3000",
methods: ["GET", "POST"] // add the methods you want to allow
}
});
https://stackoverflow.com/questions/69182297
复制