node.js - 前端和后端在不同端口上运行时,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}!`);
});
解决方案
我终于解决了错误!
问题是该请求被 Chrome 的 CORS 阻止。
我将线路更改const io = require('socket.io')(http)
为const io = require('socket.io')(http, { cors: {}});
.
现在一切正常。
推荐阅读
- python - 如果我导入它,是否可以以某种方式在一个文件中编写一个 def 函数并在另一个文件中使用它?
- javascript - 在 ReactJS/Firebase 中访问数据/结构数据
- asp.net-core - ASP .Net MVC Core 在模型列表中绑定了错误的值
- c# - 无法通过 JSON-RPC 将 GETBLOCKHASH 发布到比特币核心
- c# - 如何从 MySQL 表 C# 中正确获取数据
- ios - ObservableObject 不更新视图
- python - 用于字符识别的 ImageNet 权重?
- flutter - 颤振包在包中找不到类
- amazon-web-services - 具有 Route 53 域的 AWS S3 网站,需要通过 CloudFront 进行 https
- svelte - “无法获得 /” - 404