首先跨域解决办法
const port = 3000 const app = require('express')() const http = require('http').createServer(app) var io = require('socket.io')(http, { cors: true, withCredentials: true }) io.on('connection', (socket) => { console.log('建立鏈接') }) /* listen port also tried app */ http.listen(port, () => { console.log(`working on ${port}`) })
跨域的问题很好解决,但是接下来的问题,花了几个小时找文档才解决。。
withCredentials: true, 这个东西 表示每次请求可以携带 cookie 和 session
大概意思就是前端请求如果携带Cookie信息,那么后端Access-Control-Allow-Origin不能为 *,如果需要携带cookie的话,需要设置对应域名地址就可以了。
import VueSocketIO from 'vue-socket.io' Vue.use( new VueSocketIO({ debug: true, connection: 'http://localhost:3000/', vuex: { store, }, }) )
这样使用插件是不行的。看了文档才知道可以设置withCredentials这个玩意的。
import Vue from 'vue' import store from './store' import App from './App.vue' import VueSocketIO from 'vue-socket.io' import SocketIO from 'socket.io-client' const options = { path: '/my-app/' }; //Options object to pass into SocketIO Vue.use(new VueSocketIO({ debug: true, connection: SocketIO('http://metinseylan.com:1992', options), //options object is Optional vuex: { store, actionPrefix: "SOCKET_", mutationPrefix: "SOCKET_" } }) );
在这里的options里面设置
import VueSocketIO from 'vue-socket.io' import SocketIO from 'socket.io-client' const options = { withCredentials: false } //Options object to pass into SocketIO Vue.use( new VueSocketIO({ debug: true, connection: SocketIO('127.0.0.1:3000', options), //options object is Optional vuex: { store, }, }) )
发表评论
侧栏公告
寄语
譬如朝露博客是一个分享前端知识的网站,联系方式11523518。
热评文章
标签列表
热门文章
友情链接