vue+nodejs+express使用socket.io并解决跨域问题

从查到的普遍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')
})

最后终于顺利看到结果啦!
在这里插入图片描述在这里插入图片描述

  • 1
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值