【问题标题】:React- can't connect to server socketReact-无法连接到服务器套接字
【发布时间】:2021-04-19 23:17:45
【问题描述】:

我构建了一个服务器和客户端。 客户端正在尝试通过套接字连接到服务器但是我在控制台中收到以下错误:

Access to XMLHttpRequest at 'http://localhost:5000/socket.io/?EIO=4&transport=polling&t=NS2s-Z_' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

服务器:

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('connection',(socket) =>{
    console.log('[Server] We have new connection !!!');
    socket.on('disconnect',()=>{
        console.log('[Server] WeUser has left !!!')
    });
});

app.use(router); 

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

客户:

let socket;
const Chat= ({location}) =>{
    const ENDPOINT ='localhost:5000';
    const [name,setName] = useState('');
    const [room,setRoom] = useState('');
    useEffect(()=>{
        const {name,room} = queryString.parse(location.search) // get url
        socket = io(ENDPOINT);
        //Update state with new name and room
        setName(name);
        setRoom(room);
        console.log(socket);
        // socket.emit('ERROR');
    },[ENDPOINT,location.search]);
    return (<h1>Chat</h1>);
}

起初,我确定问题在于服务器与客户端请求不在同一个端口上。但遗憾的是,事实并非如此。

编辑: 我已经将两个端口都更改为 3000 并且它似乎可以工作,但是,对于任何其他端口它都不是。有没有办法因为操作系统权限,客户端无法发送 ack 到连接

【问题讨论】:

  • 确定不是因为端口号不同吗? Different port numbers, if specified, mean different origins,所以,CORS。
  • 也许我错了,我已经将服务器端口更改为 3000 并将客户端 ENDPOINT 更改为 localhost:3000,并且它的工作原理。有没有办法与OS相关的问题?
  • 您的操作系统可能会阻止对端口 5000 的请求,是的。检查您的防火墙设置。

标签: node.js reactjs express socket.io


【解决方案1】:

我遇到了同样的问题,你可以尝试在客户端添加传输,对我有用

const socket = io("localhost:5000", { transports: ["websocket"] });

【讨论】:

  • 你能解释一下是什么问题吗?
  • 不幸的是,我并不真正理解这个问题,我已经尝试过文档中的内容,但没有成功,所以我找到了解决方案 here 我描述的方式是最快的测试方式所以我没有进一步研究它
【解决方案2】:

您的 express 需要启用 CORS。这里是如何。安装这个包:

npm i cors

需要它:

const cors = require('cors');

然后在您的const app = express(); 正下方粘贴:

app.use(cors());

【讨论】:

  • 我试过了,但是我得到了同样的异常:polling-xhr.js:202 GET http://localhost:5000/socket.io/?EIO=4&amp;transport=polling&amp;t=NS310zM net::ERR_FAILED ______AND_____:Access to XMLHttpRequest at 'http://localhost:5000/socket.io/?EIO=4&amp;transport=polling&amp;t=NS310zM' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource
  • @GuyArilei 当您在浏览器的地址栏中拉出此网址时会发生什么? http://localhost:5000/socket.io/?EIO=4&amp;transport=polling&amp;t=NS310zM
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-02-08
  • 2018-11-29
  • 2016-03-10
  • 1970-01-01
  • 2015-11-14
  • 2021-02-18
  • 2018-03-15
相关资源
最近更新 更多