vue使用websocket?

代码

<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 跟 上面的接口 实时通讯,大佬们遇到这样的情况要怎么解决

阅读 838
2 个回答

参考这个


const socket = new WebSocket('wss://example.com/socket');

socket.addEventListener('open', (event) => {
  // 在握手阶段添加Authorization头
  socket.send('Authorization: Bearer ' + YOUR_TOKEN);
});

socket.addEventListener('message', (event) => {
  // 处理接收到的消息
  console.log('Received:', event.data);
});

websocket正常连接应该是返回101状态码而不是200
image.png
用这个网站看看websocket地址是否能正常连接
https://wstool.js.org/

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题