socket.io跨域踩坑
生活随笔
收集整理的這篇文章主要介紹了
socket.io跨域踩坑
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
一、koa結合socket.io
后端代碼:
// 引入依賴 const koa = require("koa"); // 初始化koa const app = new koa(); // 開啟 http var server = require("http").createServer(app.callback()); // 初始化 socket const io = require("socket.io")(server, { cors: true }); // 監聽 io.on("connection", (socket) => {console.log("有人鏈接");//接收數據socket.on('send', function (data) {console.log(data);// 發送數據socket.emit('resend', {msg: `你好${data.msg}`,code: 200});}); }); server.listen(3000);前端代碼:
<template><div class="hello"><input type="text" v-model="msg"><button @click="sendMsg">發送</button></div> </template><script> import io from 'socket.io-client' export default {name: 'HelloWorld',data () {return {msg: 'Welcome to Your Vue.js App'}},mounted () {const socket = io('ws://localhost:3000')this.socket = socketwindow.socket = socketsocket.on('connect', function () {console.log('連接建立成功了!')})socket.on('disconnect', function () {console.log('斷開連接了')})socket.on('resend', function (data) {console.log(data)})},methods: {sendMsg () {// 發送信息給服務端this.socket.emit('send', {msg: this.msg})}} } </script> <style scoped></style>
二、express 結合 socket.io
var app = require('express')(); var http = require('http').Server(app); var io = require('socket.io')(http, { cors: true });app.get('/', function(req, res){res.send('<h1>你好web秀</h1>'); });io.on('connection',function(socket) {console.log("有人鏈接");//接收數據socket.on('send', function (data) {console.log(data);// 發送數據socket.emit('resend', {msg: `你好${data.msg}`,code: 200});}); });http.listen(3000, function(){console.log('listening on *:3000'); });前端代碼:
<template><div class="hello"><input type="text" v-model="msg"><button @click="sendMsg">發送</button></div> </template><script> import io from 'socket.io-client' export default {name: 'HelloWorld',data () {return {msg: 'Welcome to Your Vue.js App'}},mounted () {const socket = io('ws://localhost:3000')this.socket = socketwindow.socket = socketsocket.on('connect', function () {console.log('連接建立成功了!')})socket.on('disconnect', function () {console.log('斷開連接了')})socket.on('resend', function (data) {console.log(data)})},methods: {sendMsg () {// 發送信息給服務端this.socket.emit('send', {msg: this.msg})}} } </script> <!-- Add "scoped" attribute to limit CSS to this component only --> <style scoped></style>
注意:
如果出現跨域報錯,可以參考以下解決方案:
總結
以上是生活随笔為你收集整理的socket.io跨域踩坑的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 四、scrapy爬虫框架——scrapy
- 下一篇: docker 虚拟机搭建mongodb一