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'

1 Answer 1

6

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/

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.