链接:https://www.jianshu.com/p/ab47f613e8c6
首先写一个公共方法 socket.js
functiongetSocket(url, params, callback) {
let socket
if(typeof(WebSocket) === 'undefined') {
console.log('您的浏览器不支持WebSocket')
} else{
console.log('您的浏览器支持WebSocket')
// 初始化 WebSocket 对象,指定要连接的服务器地址与端口建立连接
socket = newWebSocket(url)
// 打开事件
socket.onopen = function() {
console.log('Socket 已打开')
socket.send(params)
}
// 获得消息事件
socket.onmessage = function(msg) {
// 发现消息进入, 开始处理前端触发逻辑
callback(msg, socket)
}
// 关闭事件
socket.onclose = function() {
console.log('Socket 已关闭')
}
// 发生了错误事件
socket.onerror = function() {
console.log('Socket 发生了错误,请刷新页面')
// 此时可以尝试刷新页面
}
}
}
export {
getSocket
}
使用
test.vue
<script>
import {getSocket} from '@/utils/socket.js'
export default{
data() {
return{
wsData: {}, // 保存 websocket 数据对象
form: { // 表单
name: '',
age: ''
}
}
},
beforeDestroy() {
this.wsData.close()// 关闭 websocket
},
created() {
this.getSocketData()
},
methods: {
// 获取数据
getSocketData() {
let params = this.form
getSocket(
`ws://path`,
JSON.stringify(params),
(data, ws) =>{
console.log(data, ws)
// 保存数据对象, 以便发送消息
this.wsData = ws
}
)
},
// 发送数据
sendSocketData() {
let params = this.form
params.name = 'xx'
params.age= '18'
this.wsData.send(JSON.stringify(params))
}
}
}
</script>
vue跨域解决方法使用axios请求
第一步骤
在vue.config.js 文件中 module.exports = { } 中添加
devServer: {
proxy: {
'/profile': { //指定 路径 要 跨域请求地址
// 在本地会创建一个虚拟服务端,然后发送请求的数据,并同时接收请求的数据,这样服务端和服务端进行数据的交互就不会有跨域问题
// 将/api开头的url转发到target上。
target: ' https://sso.www.eee.cn/profile',// 跨域请求地址
changeOrigin: true, //虚拟的站点需要更管origin
ws: true, // 代理websockets
secure: true, // 如果是https接口,需要配置这个参数
pathRewrite: {
// 顾名思义,将/api重写为 / 此时url变为 http://192.168.101.110:8888/ 而不是 http://192.168.101.110:8888/api
'^/profile': ''
}
}
}
第二步骤
在封装axios请求中设置
const service = axios.create({
baseURL: '/profile',//定义要跨域的接口路径
withCredentials: true,//是否支持跨域
timeout: 500000, // request timeout
headers: {
'Cache-Control': 'no-cache',
'Content-Type': 'application/x-www-form-urlencoded'
}
})
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)