简体   繁体   中英

Alert() pops up twice in axios interceptor (Vue.js)

In my Vue app, I instantiate a single instance of axios and use it across the app for HTTP requests. I have set up a response interceptor which checks if any response from the backend is 401 unauthorized , and if so, shows an alert message. This basic flow has been implemented, but you need to hit "OK" on the alert message twice for it to go away, and I am not sure why.

Axios instance:

import axios, { AxiosError, AxiosInstance, AxiosResponse } from 'axios';

const axiosInstance: AxiosInstance = axios.create();

axiosInstance.interceptors.response.use(
  (response: AxiosResponse) => response,
  (error: AxiosError) => {
    if(error.response && error.response.status === 401) {
      alert('There has been an issue. Please log out and then log in again.');
      return Promise.reject(error);
    }
  }
);

export default axiosInstance;

The request whose response is being intercepted:

import axiosInstance from 'axios-instance';

  public async getloggedInUserId() {
    await axiosInstance.get('/sessions.json')
      .then((response) => {
        if(response.data.user_id) {
          this.SET_USER_ID(response.data.user_id);
        }
      });
  }

I've read this thread, but my issue seems to be different: Javascript alert shows up twice

I've tried changing the return statement from return Promise.reject(error);to return false; but that did nothing for me.

As Phil suggested in the comment above, looking at at the Network tab in the browser console helped me solve the issue. The console showed how each component in the page was being loaded along with the resulting response code. In short, two processes were actually returning 401 , which was the reason why the alert was being called twice.

I have decided to move the code that calls alert from a global axios interceptor (called whenever any process returns 401 ) to a .catch block inside one specific axios process, so that it only gets called once.

Your promise throws error in axios error interceptor, and error called second times.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM