首页 > 解决方案 > 前端和后端在不同端口上运行时,Socket.io 客户端请求失败

问题描述

我想将 Socket.io 与 React 前端和 NodeJS & Express 后端一起使用,但它们都在不同的端口上运行以进行开发(Fontend:3000;后端:8080)。

当 Socket.io-Client 加载后,我的前端执行var socket = io('http://localhost:8080');,然后自动向http://localhost:8080/socket.io/?EIO=4&transport=polling&t=NSlH7of. 该请求通常应该返回类似0{"sid":"XXX","upgrades":["websocket"],"pingInterval":25000,"pingTimeout":5000}但 Chrome 开发工具说状态是(failed) net::ERR_FAILED. 开发工具中也没有可用的响应。

但是,当我在我的 HTTP 客户端中运行 GET 请求时,它会返回我期望它返回的内容。

该错误看起来像是由 Socket.io-Client 引起的,但除了失败的 GET 请求之外,我没有收到任何错误。当我在一个端口上运行所有内容时(前端由后端的 webpack 提供服务),请求按预期通过。

我将不胜感激任何帮助!谢谢!

服务器.js

const express = require('express');
const app = express();
const http = require('http').Server(app);
const io = require('socket.io')(http);

//Serve static react app
app.use(express.static('dist'));
app.use('/app', express.static('dist'));
app.get('/', (req, res) => {
    res.sendFile(path.join(__dirname + '../../../' + '/dist/index.html'));
});

io.on('connection', (socket) => {
    console.log('Connected')
    socket.on('join-game', (gameId, userId) => {
        console.log(gameId, userId);
    })
})

http.listen(process.env.PORT || 8080, () => {
    console.log(`Listening on port ${process.env.PORT || 8080}!`);
});

标签: node.jsexpresssocketssocket.io

解决方案


我终于解决了错误!

问题是该请求被 Chrome 的 CORS 阻止。

我将线路更改const io = require('socket.io')(http)const io = require('socket.io')(http, { cors: {}});.

现在一切正常。


推荐阅读