The attempt to establish a WebSocket connection to 'ws://localhost:4000/graphql' was unsuccessful:

Encountering the Websocket failed to Connect error on both the client and server sides (shown in image below) has left me puzzled for the past 2 days. I have not made any other Websocket configurations apart from the one specified in the apollo client. Any assistance with this issue would be greatly appreciated. Feel free to ask if you require additional code snippets.

The setup involves a Vue app client connecting to a graphql apollo server. Here's a snippet of the apolloclient configuration:

// Apollo packages
    import { ApolloClient } from "apollo-boost-upload";
    import { WebSocketLink } from "apollo-link-ws";
    import { HttpLink } from "apollo-link-http";
    import { InMemoryCache } from "apollo-cache-inmemory";
    import { split } from "apollo-link";
    import { getMainDefinition } from "apollo-utilities";
    import VueApollo from "vue-apollo";
    Vue.use(VueApollo);    
    wsLink = new WebSocketLink({
      uri: "ws://localhost:4000/graphql", // use wss for a secure endpoint
      options: {
        reconnect: true,
      },
    });
    
    const link = split(
      // split based on operation type
      ({ query }) => {
        const definition = getMainDefinition(query);
        return (
          definition.kind === "OperationDefinition" &&
          definition.operation === "subscription"
        );
      },
      wsLink,
      httpLink
    );
    
    // Cache implementation
        
    export const defaultClient = new ApolloClient({
      // uri: "http://localhost:4000/graphql",
      link,
      cache: new InMemoryCache(),
      fetchOptions: {
        credentials: "include",
      },
     
      request: (operation) => {
        // if no token in local storage, add it
        if (!localStorage.anaceptToken) {
          localStorage.setItem("anaceptToken", "");
        }
        // operation adds the token to authorizatrion header, which is sent o backend
        operation.setContext({
          headers: {
            authorization: "Bearer " + localStorage.getItem("anaceptToken"),
          },
        });
      },
      onError: ({ graphQLErrors, networkError }) => {
        if (networkError) {
          console.log("[networkError]", networkError);
        }
        if (graphQLErrors) {
          for (const error of graphQLErrors) {
            console.dir(error);
            console.log(error);
            if (
              error.name === "AuthenticationError" ||
              error.message === "jwt expired"
            ) {
              // set auth error in state
              store.commit("setError", error);
              // signout user to clear error
              store.dispatch("signUserOut");
            }
          }
        }
      },
    });

vue config file

const { defineConfig } = require("@vue/cli-service");
const NodePolyfillPlugin = require("node-polyfill-webpack-plugin");
module.exports = defineConfig({
  pluginOptions: {
    apollo: {
      enableMocks: true,
      enableEngine: true,
    },
  },
  transpileDependencies: ["vuetify"],
  chainWebpack: (config) => {
    config.performance.maxEntrypointSize(400000).maxAssetSize(400000);
    new NodePolyfillPlugin();
  },
});

https://i.sstatic.net/n9UWl.png

Answer №1

give it a go at localhost 4004, you might be surprised

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Differences Between 'this' and 'self' in Classes

I am currently working with ES6 Classes and I'm struggling to grasp why I am able to access the this variable within one of the methods. //CODE class Form{ constructor(){ var self = this; } assemble(){ log(self); ...

Attempting to spread a non-iterable instance is invalid. For non-array objects to be iterable, they must have a [Symbol.iterator]() method

data(){ return { tables:[] } }, mounted(){ this.fetchData() }, methods:{ fetchData(){ var subscription = web3.eth.subscribe('logs', { address: '0x123456..', topics: ['0x12345. ...

How to access a class from another JavaScript file using a function call

The title may seem strange, but I will do my best to explain the situation clearly. I have a website with a navigation bar where each tab corresponds to a different php file. All the files share a common js and css file. The directory structure is as foll ...

What is causing the ESLint error when trying to use an async function that returns a Promise?

In my Next.js application, I have defined an async function with Promise return and used it as an event handler for an HTML anchor element. However, when I try to run my code, ESLint throws the following error: "Promise-returning function provided t ...

What exactly does the combination of {on, attrs} create within Vue/Vuetify?

Although this question may have been asked before, I am still struggling to grasp its meaning. Can you help me understand it better? <v-dialog v-model="dialog" width="500" > <template v-slot:activator=&quo ...

CKEditor - extracting modified content with its associated HTML markup

I am currently developing my own custom Drupal plugin and I recently reviewed the code provided in the API for change events: editor.on('change', function (evt) { console.log(this.getData()); }); Using this code snippet, I am able to vi ...

Send an AJAX request to the specified `httpost` action method without any page refresh to load the

Today I have an interesting challenge that's been a brain teaser for me. While I may not be an expert in ASP.Net MVC4, I'm excited to tackle something new. The ultimate goal is to create a dynamic tree view for partial pages within a standard pag ...

Organizing outcomes from a for each function into an array using javascript

I have a form with multiple values of the same name, and I need to arrange this data in an array before sending it via AJAX. However, when I try to do this using the .push function, I encounter an error that says "Uncaught TypeError: dArray.push is not a f ...

Tips for adding event listeners to dynamically-loaded content using AJAX

I need help with the following code snippet: $("#contantainer").load("some_page.txt"); Inside some_page.txt, I have the following content: <div class="nav"> <ul id="nav_ul"> <li><a class="nav_a" href="#home" id="home"> ...

Moving through content on a single page

import React, { Component, useState } from "react"; import { Content, List, ListItem, Left, Right, Icon, Container, Header, Body, Button, Title, } from "native-base"; //Chapter One expor ...

Oops! Looks like we have a little hiccup in our code. The Route.post() function in our server.js file is expecting

Currently in the process of setting up a nodeJS server using express. I have two backend files: one named account.js in a directory called routes, and the other named server.js. However, I'm encountering an issue where it fails to run due to an error ...

Having trouble displaying information in JavaScript after using getScript() to retrieve data from an API containing a JSON block database

I'm a newcomer to the world of Ajax/json/jquery and I find myself with a few inquiries. Currently, I am working with an API located at which contains a JSON block that looks something like this [{"id":"1","FirstName":"Micheal","LastName":"Kooling"}, ...

Utilizing Color-Thief in a Vue.js Environment: A Step-by-Step Guide

I'm attempting to bring in the color-thief package from NPM (https://github.com/lokesh/color-thief) using this script: import ColorThief from 'colorthief' However, when I try to instantiate new ColorThief(), it gives me an error stating th ...

Using AJAX and jQuery, the result is retrieved and inserted into a <div> element

Having trouble populating a DIV with the result of a simple GET request using AJAX and jQuery. What could be causing the issue? <head> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"> </script> <scrip ...

Is it acceptable for Single Page Web Apps to have multiple requests at startup?

I've been dedicated to developing a Single Page Web App (SPA) recently. The frontend is built with BackboneJS/Marionette, while the backend is powered by Java Spring :(. However, I've noticed that the application's start time could be sluggi ...

The emulator failed to launch because it could not find any emulators listed as an output of the `emulator -list-avds` command

Hello everyone, I've recently ventured into the world of React Native and managed to successfully install and launch the emulator. However, I encountered a problem when attempting to run the command react-native run-android. The console output display ...

Fetching dynamic JavaScript generated by PHP

I am creating a lightweight website and I have a piece of javascript code that I want to convert into a module by putting it in a separate file. This way, the code will only be loaded after a specific onClick event occurs. Successfully loading the javascr ...

Calling a JavaScript function from server-side code (without using startup scripts)

In essence, my objective is as follows: Initiate deletion of a record upon button click. Delete the record only if a specific column (Location) is null (working perfectly). If the specific column is not null, prompt the user for confirmation before proce ...

Adding new options to a multi-select dropdown in Vue.js when fetching data using an

Greetings! I've been utilizing a modified wrapper to manage a multiple select for vue.js. My goal is to change the value of 'this' inside the vue component. Below is the snippet of my code. <select2-multiple :options="car_options" v-mode ...

Python and Javascript clashing with one another

(Updated question for clarity). I am currently developing a flask app game that involves users inputting guesses via the web browser. The backend, which runs on Python, checks these guesses and provides feedback to the user about their accuracy. Additional ...