Dealing with net::ERR_CONNECTION_REFUSED in Axios on a Vue.js platform

Here's the code I'm using for my connection request:

doLogin(this.login).then(response => {
        var token = response.data.token;
        localStorage.setItem('AUTH_TOKEN', JSON.stringify(token));
        this.$router.push({name: 'Devices'});
        });
      }).catch(error => {
        console.log(error.response.data.message);
      });

The catch() part is effective in handling HTTP errors (like 400, 404, 403, etc.). However, when the server is offline, the script throws a net::ERR_CONNECTION_REFUSED error. Is there a way to handle this error and inform the front-end user that the server is currently offline?

Just in case, here is the doLogin() function:

function doLogin(data) {
  const url   = 'http://localhost:3000/authenticate';
  return axios.post(url,data);
}

Answer №1

Consider implementing the following code snippet within the catch block:

catch(error => {
        if (!error.response) {
            // handle network errors
            this.errorMessage = 'Error: Network Issue';
        } else {
            this.errorMessage = error.response.data.message;
        }
      })

Answer №2

You have the option to utilize interceptors:

axios.interceptors.response.use(
    response => {
        return response
    },
    error => {
        if (!error.response) {
            console.log("Ensure that your internet connection is working properly.");
        }

        return Promise.reject(error)
    }
)

Answer №3

It is important to perform the validation mentioned by @chithra within the .then() block. I have encountered an unusual problem while testing requests when my servers are down, where the "response" appears to be successful.

Furthermore, ensure that within the .then() block, you check for response.status instead of response.error

Answer №4

Utilizing interceptors is a powerful tool

Custom Interceptors

yourCustomInstance.interceptors.response.use(
  response => response,
  error => {
      if (error.code === 'ERR_CONNECTION') {
          alert("Connection lost");
      }


      return Promise.reject(error)
  }
)

Answer №5

Utilizing npm as the standard package manager for Node.js, a JavaScript runtime environment.

To install Axios using npm:

npm i axios

After installation, ensure to import Axios in your src/App.vue file

import axios from 'axios';

You will then need to invoke it within a lifecycle hook. In this example, we are utilizing the beforeCreate() lifecycle hook so that we can access sensitive data and active events associated with it.

 data() {
return {
  network: false,
}; },
beforeCreate() {
axios
  .get("http://localhost:13172/api/product/getproducts")
  .then((response) => {
    console.log(response);
    this.network = true;
  })
  .catch((error) => {
    console.log(error), (this.network = false);
  }); }

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

Loading Images in Advance with jQuery, Native JavaScript, and CSS

After successfully implementing a method to hover on a small image and load an additional image to the right side of the page, I am now looking to enhance user experience by preloading images. Is there a way to preload an image using JQuery, allowing it t ...

TS2339 Error: The property 'Default' is not a valid property for type 'string'

Hello, I am a beginner with Angular 2. I have encountered some issues that I need help with: Error Messages: app/components/playing-cables/-update.ts(82,12): error TS2339: Property 'options' does not exist on type 'jQuery'. app/compone ...

Is the window frozen while Ajax processes the request?

When I make an ajax request that may take a significant amount of time to process on the server-side, I want to display a loading image during the request. However, the loading image is not showing up while the ajax request is processing. var ref = create ...

Implementing dynamic content updating in WordPress by passing variables and utilizing AJAX

Currently, I am working on a shopping page that displays a list of all the stores. To streamline the user experience, I have created a sidebar containing various categories and implemented pagination within the store listings. These lists are generated thr ...

What is the best way to retrieve a JSON element obtained from a Parse.com query?

I'm encountering difficulties when attempting to access a specific JSON element that I receive in response from a query made into a Parse.com Class. Despite reading through various questions and answers on similar topics, I have yet to find a solutio ...

Efficiently improving performance with the JavaScript method .scroll()

I have a scrollable container filled with numerous elements and a dropdown menu with various options. My goal is to dynamically change the dropdown's selected option based on the container's scroll position. What is the most effective way to ac ...

React State RefreshIs this rewrite good enough?

Displayed above is an image of an object containing two UI controls stored as this.state.controls. Initially, the state values are set with data received before componentDidMount. Updates to the controls' state values are triggered by an event, which ...

You are receiving an error message stating that the requested resource does not have the 'Access-Control-Allow-Origin' header present

Looking to retrieve the feed from a news website, I decided to utilize google's feed API to convert the feedburner feed into json. By using the following URL, you can fetch 10 posts from the feed in json format. http://ajax.googleapis.com/ajax/service ...

Experiencing issues utilizing vue.js to retrieve information from a REST API

Using vue.js, I am attempting to fetch data from a rest api but encountering issues. Unfortunately, the response data is not being displayed and no error status is shown either. It's puzzling trying to identify what may have gone wrong. Below is my i ...

Upon its second use, Ajax is loaded with cached data

Imagine a table with multiple rows, each row containing a SHOW button that reveals hidden content when clicked. The hidden div (with the classname "Content") loads the content of a second page using ajax and the id of the corresponding table row. However, ...

I'm experiencing some issues with my scene in ThreeJS - the HDR background isn't displaying, and my cube

<style> body { margin: 0; } </style> <script async src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="afcadc82c2c0cbdac3ca82dcc7c6c2dcef9e8199819c">[email protected]&l ...

"Unlock the secret to effortlessly redirecting users to a designated page when they click the browser's back

So I'm facing the challenge of disabling the browser back button on multiple routes and sending requests to the backend is resulting in inconsistent behavior. I don't want to create a multitude of similar API requests each time. Currently, I have ...

Dynamic animation utilizing Angular JS and Snap SVG

Attempting to achieve a seamless and continuous animation using AngularJS and Snap SVG, I believed I had successfully resolved the issue as my animations ran smoothly for hours on end. However, leaving my solution running over the weekend in Chrome, Opera, ...

"Encountering problems with location search function on Instagram API for retrieving posts

I've been working on integrating two APIs – Instagram and Google Maps. While I've managed to get everything functioning smoothly, there's an issue with displaying "up to 20 pictures" around a specific location. I'm unsure why this in ...

Retrieve the thousand separator for numbers using Angular in various languages

When using the English locale, numbers appear as follows: 111,111,222.00, with a comma as the thousand separator and a point as the decimal separator. In languages like German, the same number would be represented as 111.111.222,00, reversing the positions ...

Sending a request for the second time may result in data duplication

To upload a file to the server, I use the following code snippet: var fd = new FormData(); fd.append('folder', 'html'); fd.append('permission', 0); fd.append("file", file, file.name); After selecting the file from an input f ...

The error message "Property 'id' is missing on type 'T'" is indicating the absence of the 'id' property in the

I am currently working on a React component that serves as a table and is designed to handle various types of data. The structure of the component is defined as follows: type SimpleTableProps<T> = { data: Array<T>; ... }; const SimpleTabl ...

RegEx not triggering Mongoose hooks

When performing queries on my mongo collections, I am attempting to call specific hooks for them. DispatchRequest.findOneAndUpdate({user_name:"umesh"},{email:"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="cdac8 ...

Using HTML and CSS to capture user input data and store it in an array

I've created a form that allows users to add and remove multiple fields, ranging from one to three. My goal is to retrieve the form data and store it in an array. index.html <!DOCTYPE html> <html lang="en"> <head> ...

What steps should be taken to identify a new path following a call to router.navigate?

Trying to interrupt a route change using a router guard. When I use: this.router.navigate([“myApp/userProfiles”]); After calling this, it passes through the CanDeactivate interface of the guard. The guard then needs to determine the actual destinatio ...