简体   繁体   English

axios拦截器中alert()弹出两次(Vue.js)

[英]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.在我的 Vue 应用程序中,我实例化了 axios 的单个实例,并在整个应用程序中使用它来处理 HTTP 请求。 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.我已经设置了一个响应拦截器,它检查来自后端的任何响应是否为401 unauthorized ,如果是,则显示一条警告消息。 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.这个基本流程已经实现了,但是你需要在警告消息上点击“确定”两次才能让它离开 go,我不确定为什么。

Axios instance: Axios 实例:

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我读过这个帖子,但我的问题似乎有所不同: Javascript 警报出现两次

I've tried changing the return statement from return Promise.reject(error);我试过从return Promise.reject(error);更改返回语句to return false; 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.正如 Phil 在上面的评论中所建议的那样,查看浏览器控制台中的“网络”选项卡帮助我解决了这个问题。 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.简而言之,实际上有两个进程返回401 ,这就是alert被调用两次的原因。

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.我决定将调用alert的代码从全局 axios 拦截器(每当任何进程返回401时调用)移动到一个特定 axios 进程内的.catch块,以便它只被调用一次。

Your promise throws error in axios error interceptor, and error called second times.您的 promise 在 axios 错误拦截器中抛出错误,并且第二次调用错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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