WebSocket 不是用 NuxtJS 定义的

WebSocket is not defined with NuxtJS

所以我想使用 NuxtJs 框架使用 VueJs 制作一个网络套接字客户端,这是我的组件

export default {
  data() {
    return {
      connection: null,
    }
  },
  created() {
    console.log("Starting connection to WebSocket Server")
    this.connection = new WebSocket("wss://echo.websocket.org")

    this.connection.onmessage = function(event) {
      console.log(event);
    }

    this.connection.onopen = function(event) {
      console.log(event)
      console.log("Successfully connected to the echo websocket server...")
    }
  },
  head() {
    return {
      title: 'Web Socket',
      meta: [
        {
          hid: 'description',
          name: 'description',
          content: 'Web socket'
        }
      ]
    }
  }
}

我收到了这条消息

我在浏览器上使用 Ms Edge,我尝试使用 vue-native-socket 和其他套接字包,但仍然出现相同的错误 'Websocket not defined'

我不是 Websocket 专家,但据我所知,这是仅在客户端可用的东西。
您可以尝试跟进这个答案:

created() {
  if (process.client) {
    // the code in this block will only run on client side
    console.log("Starting connection to WebSocket Server")
    this.connection = new WebSocket("wss://echo.websocket.org")

    this.connection.onmessage = function(event) {
      console.log(event);
    }

    this.connection.onopen = function(event) {
      console.log(event)
      console.log("Successfully connected to the echo websocket server...")
    }
  }
}

这将防止在 created() 钩子中编写的代码在服务器端和客户端都被触发(因此在服务器端发生错误)。因为 created() 在服务器端和客户端都可用,如此处解释:https://nuxtjs.org/docs/2.x/concepts/nuxt-lifecycle/