代码
<template>
<div>
<el-button @click="connectToWebSocket">点击发送</el-button>
</div>
</template>
<script>
import { baseURL } from '@/config'
import request from '@/utils/request'
export default {
data() {
return {
// wsUrl: 'ws://192.168.1.109:8900/applet/user/chat/176', // ws地址
// socket: null, // ws实例
socket: null,
// authorizationToken: 'your-authorization-token', // 假设你已经有了授权令牌
form: {}
};
},
beforeDestroy() {
if (this.socket) {
this.socket.close();
}
},
mounted() {
this.refreshToken()
},
methods: {
refreshToken() {
const that = this
request({
url: `${baseURL}captcha`,
method: 'get',
}).then(function (result) {
if (result.success) {
that.form.csrfToken = result.data.csrfToken
}
})
},
connectToWebSocket() {
this.socket = new WebSocket('ws://192.168.1.109:8900/applet/user/chat/176');
this.socket.onopen = () => {
// 连接打开后,发送包含授权信息的消息给服务器
const authMessage = {
authorizationToken: this.form.csrfToken
};
this.socket.send(JSON.stringify(authMessage));
};
this.socket.onmessage = (event) => {
console.log('Received:', event.data);
};
this.socket.onerror = (error) => {
console.error('WebSocket Error:', error);
};
this.socket.onclose = () => {
console.log('WebSocket is closed now.');
};
}
}
};
</script>
ws://192.168.1.109:8900/applet/user/chat/176是后端接口,这个接口要带上token的值,token的值放在authorization,176是userId,目前是写死,用上面的代码 在控制台里报VM10734 ceshi.vue:40 WebSocket connection to 'ws://192.168.1.109:8900/applet/user/chat/176' failed: Error during WebSocket handshake: Unexpected response code: 200,尝试过几种写法都没有效果
想要的效果是WebSocket 跟 上面的接口 实时通讯,大佬们遇到这样的情况要怎么解决
参考这个