javascript - Axios - 设置拦截器以在出错时重试原始请求

标签 javascript vue.js axios vuex

我需要为我所有的 axios 调用设置一个全局拦截器。我在 vuex 操作中定义它们,如果有 429 状态代码,我需要调用一个操作,然后在执行该操作后,重试原始请求。我正在学习拦截器,但我不知道如何正确设置它,以及它是否可以在 export default 之外工作。谁能帮帮我?

axios.interceptors.use( (response) => {
// if no status error code is returned get the response
  return response
}, (error) => {
  console.log(error)
  // here I need to retry the ajax call after that my loadProxy action is made and a 429 status code is sent from the server
  return Promise.reject(error);
})

export default new Vuex.Store({
 actions: {
  loadProxy({ commit }) {
  // here I have an axios get request to fetch a proxy from an API 
  },
  fetchData({ commit, state }) {
  // here I fetch the data to use in my app, sometimes due to many requests I need to refresh the proxy ip to let the app continue working
  }
 }
})

最佳答案

Axios拦截器中的response对象包含一个config对象。 ( See here )

您可以使用它来重新发起具有原始配置的请求。

一个例子:

axios.interceptors.response.use((response) => {
    return response;
}, (error) => {
    if (error.response.status === 429) {
        // If the error has status code 429, retry the request
        return axios.request(error.config);
    }
    return Promise.reject(error);
});

要在拦截器回调中使用 Vuex 操作,您可以先将商店定义为变量,然后在回调中调用调度函数。像这样:

const store = new Vuex.Store({
   // define store...
})

axios.interceptors.response.use((response) => {
    return response;
}, (error) => {
    if (error.response.status === 429) {
        store.dispatch("YOUR_ACTION");
        return axios.request(error.config);
    }
    return Promise.reject(error);
});

export default store;

关于javascript - Axios - 设置拦截器以在出错时重试原始请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63584307/

相关文章:

vue.js - 如何在 vuelidate 验证中使用条件运算符?

java - axios、Spring boot 和 base64 的问题

Javascript 成员函数超出范围

javascript - 通过地址栏加载远程 JavaScript 文件

vue.js - Vue 实例会丢失其旧属性吗?

javascript - 带过滤器的 Vue JS axios 请求 - this.XX.filter 不是函数

reactjs - 使用 jest typescript 的 Axios 模拟类型

javascript - 固定位置直到滚动

javascript - javascript中 'use strict'的内部工作

javascript - Chartjs-Vue 图表为空