赞
踩
最近做项目,前台是react,后台是express+nodejs,用到 socket.io 做聊天功能。
报错:问题大意指跨域了
客户端代码:
import io from 'socket.io-client'
// 连接服务器, 得到与服务器的连接对象
const socket = io('ws://localhost:4000')
服务器端代码:
module.exports = function (server) {
const io = require('socket.io')(server)
io.listen(4001)
//监视客户端与服务器的连接
io.on('connection', function (socket) {
console.log('客户端连接上了服务器')
})
}
方法一:给 socket.io 赋值一个新的端口。
const _io = require('socket.io')(server)
_io.listen(12312)
参考博客:https://segmentfault.com/q/1010000009849667
没解决我的问题!
方法二:看到有人说查文档发现部署到服务器必须写真实服务器 ip 地址,不能写 hostname
原本的代码如下:
const socket = io('ws://localhost:4000')
修改的代码如下:
const socket = io('ws://xxxx.xxxx.xxxx.xxxx:4000')
参考博客:https://blog.csdn.net/a1059526327/article/details/106906059
没解决我的问题!!
方法三:在我们初始化 socket.io 的时候 加上一句 cors:true
// socket 初始化
const io = require("socket.io")(server, { cors: true })
参考博客:https://www.79bk.cn/article/62a686f9/
出现了新的报错!!!
方法四:重新下载 socket.io-client
npm i socket.io-client -s
看到篇博客说客户端中 import io from 'socket.io-client'
引入的 socket.io-client 是包含在 socket.io 中的,我之前也没有单独安装 socket.io-client 依赖,也是直接 npm install socket.io
,现在的意思就是 socket.io 中包含的 socket.io-client 与我们要用的 socket.io-client 不同,需要重新下载。
参考博客:https://blog.csdn.net/ZuoZuoDangerou/article/details/112320202
成功解决问题!
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。