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

nuk*_*o12 3 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
  }
 }
})
Run Code Online (Sandbox Code Playgroud)

haw*_*iat 10

responseaxios的拦截器中的对象包含一个对象config。(看这里

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

一个例子:

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);
});
Run Code Online (Sandbox Code Playgroud)

要在拦截器回调中使用 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;
Run Code Online (Sandbox Code Playgroud)