从查到的普遍vue使用socket.io的方法后,却出现了这个报错(为啥写那些教程的人没这种问题呢?有懂的大佬烦请能在下面评论):
Access to XMLHttpRequest at ‘http://127.0.0.1:3007/socket.io/?EIO=3&transport=polling&t=O3IWj8S’ from origin ‘http://localhost:8080’ has been blocked by CORS policy: The value of the ‘Access-Control-Allow-Origin’ header in the response must not be the wildcard ‘*’ when the request’s credentials mode is ‘include’. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.
踩过的坑
从百度、CSDN上能找到的基本都试过了,比如配置文件里加服务代理什么的,可是仍然报这个错;
还试了一下下面这种,但是会报这个错:WebSocket connection to ‘ws://localhost:3000/socket.io/?EIO=3&transport=websocket’ failed:
终于最后在谷歌上搜索出了下面的有效办法,虽然不知道为啥要这么干呜呜(有懂的大佬烦请能在下面评论)
前端vue
main.js中:
import VueSocketIO from 'vue-socket.io'
import SocketIO from 'socket.io-client'
Vue.use(
new VueSocketIO({
debug: true,
connection: SocketIO('http://127.0.0.1:3000'),//服务端地址
extraHeaders: {
'Access-Control-Allow-Credentials': true
},
allowEIO3: true,
vuex: {}
})
)
使用的vue文件中:
export default {
mounted() {
// 发送信息给服务端
this.$socket.emit('login', {
username: 'ljl',
password: '123'
})
// 接收服务端的信息
this.sockets.subscribe('relogin', data => {
console.log(data)
})
}
}
后端nodejs
const express = require('express')
const app = express()
const http = require('http').Server(app)
let path = require('path')
var cors = require('cors')
app.use(cors())
const io = require('socket.io')(http, {
cors: {
origin: 'http://localhost:8080',//前端请求地址
methods: ['GET', 'POST'],
credentials: true,
allowEIO3: true
},
transport: ['websocket']
})
io.on('connection', function (socket) {
console.log('A user connected')
//Whenever someone disconnects this piece of code executed
socket.on('disconnect', function () {
console.log('A user disconnected')
})
socket.on('login', function (obj) {
console.log(obj.username)
// send data
socket.emit('relogin', {
msg: ` Hello ${obj.username}`,
code: 200
})
})
})
http.listen(3000, function () {
console.log('listening on *:3000')
})
最后终于顺利看到结果啦!