vue socketio如何使用及跨域问题
我的后端使用的flask_socketio做服务端 前端使用的vue_socketio当客户端
vue.config.js配置
module.exports = { outputDir: process.env.outputDir, assetsDir: 'static', publicPath: '/', devServer: { open: false, host: '0.0.0.0', port: 8001, https: false, hotOnly: false, //配置代理 proxy: { //以'/api'开头的接口会转接到下面的target的ip '/api': { target: 'http://127.0.0.1:5000', // target host changeOrigin: true, // needed for virtual hosted sites ws: false, // proxy websockets pathRewrite: { //路径重写 '^/api': '/api/', // rewrite path }, logLevel: 'debug' }, '/socket.io': { target: 'http://127.0.0.1:5000', // target host changeOrigin: true, // needed for virtual hosted sites logLevel: 'debug' } } } }
在任意的.vue文件中建立连接
let socket = io({ reconnection: true, forceNew: true, transports: ['websocket'], }) socket.on('connect', function () { //连接成功绑定的事件 console.log('connect'); socket.emit('my event', {data: 'I\'m connected!'}); }); socket.on('news', function (data) { //后台提供的事件名 console.log('2222222222222') console.log(data) })