[英]Axios - setup interceptor to retry original request on error
我需要為所有 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
對象。 (見這里)
您可以使用它來重新啟動具有原始配置的請求。
一個例子:
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 操作,可以先將 store 定義為變量,然后在回調中調用 dispatch 函數。 像這樣:
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;
你可以用axios-retry做一個實驗,有一個選項
retryCondition
: 進一步控制是否應重試請求的回調
import axiosRetry from "axios-retry"
// ...
// intercept
axiosRetry(axios, {
retries: 3,
retryCondition: (error) => {
return error.response.status === 429
},
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.