2

So I want to make a web socket client using a VueJs using NuxtJs framework, this is My component

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'
        }
      ]
    }
  }
}

And I got this message Error message

I'm using Ms Edge for the browser, I tried using a vue-native-socket, and other socket package, but still get the same error 'Websocket not defined'

kissu
  • 40,416
  • 14
  • 65
  • 133

1 Answers1

4

I'm no Websocket expert, but to my knowledge, this is something available only on client side.
You may try to follow up this answer: https://stackoverflow.com/a/67751550/8816585

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...")
    }
  }
}

This will prevent the code written inside of the created() hook to be triggered on both server and client side (hence the error on the server). Because created() is available on both server and client side, as explained here: https://nuxtjs.org/docs/2.x/concepts/nuxt-lifecycle/

kissu
  • 40,416
  • 14
  • 65
  • 133