axios 請求超時,設定重新請求的完美解決方法
自從使用 Vue2 之後,就使用官方推薦的 axios 的外掛來呼叫 API,在使用過程中,如果伺服器或者網路不穩定掉包了, 你們該如何處理呢? 下面我給你們分享一下我的經歷。
具體原因
最近公司在做一個專案, 服務端資料介面用的是 Php 輸出的 API, 有時候在呼叫的過程中會失敗, 在谷歌瀏覽器裡邊顯示 Provisional headers are shown。
按照搜尋引擎給出來的解決方案,解決不了我的問題.
最近在研究 AOP 這個開發程式設計的概念,axios 開發說明裡邊提到的欄截器(axios.Interceptors)應該是這種機制,降低程式碼耦合度,提高程式的可重用性,同時提高了開發的效率。
帶坑的解決方案一
我的經驗有限,覺得唯一能做的,就是 axios 請求超時之後做一個重新請求。通過研究 axios 的使用說明,給它設定一個 timeout = 6000
axios.defaults.timeout = 6000;
然後加一個欄截器.
// Add a request interceptor axios.interceptors.request.use(function (config) { // Do something before request is sent return config; }, function (error) { // Do something with request error return Promise.reject(error); }); // Add a response interceptor axios.interceptors.response.use(function (response) { // Do something with response data return response; }, function (error) { // Do something with response error return Promise.reject(error); });
這個欄截器作用是 如果在請求超時之後,欄截器可以捕抓到資訊,然後再進行下一步操作,也就是我想要用 重新請求。
這裡是相關的頁面資料請求。
this.$axios.get(url, {params:{load:'noload'}}).then(function (response) { //dosomething(); }).catch(error => { //超時之後在這裡捕抓錯誤資訊. if (error.response) { console.log('error.response') console.log(error.response); } else if (error.request) { console.log(error.request) console.log('error.request') if(error.request.readyState == 4 && error.request.status == 0){ //我在這裡重新請求 } } else { console.log('Error', error.message); } console.log(error.config); });
超時之後, 報出 Uncaught (in promise) Error: timeout of xxx ms exceeded 的錯誤。
在 catch 那裡,它返回的是 error.request 錯誤,所以就在這裡做 retry 的功能, 經過測試是可以實現重新請求的功功能, 雖然能夠實現 超時重新請求的功能,但很麻煩,需要每一個請 API 的頁面裡邊要設定重新請求。
看上面,我這個專案有幾十個.vue 檔案,如果每個頁面都要去設定超時重新請求的功能,那我要瘋掉的.
而且這個機制還有一個嚴重的 bug,就是被請求的連結失效或其他原因造成無法正常訪問的時候,這個機制失效了,它不會等待我設定的 6 秒,而且一直在刷,一秒種請求幾十次,很容易就把伺服器搞垮了,請看下圖, 一眨眼的功能,它就請求了 146 次。
帶坑的解決方案二
研究了 axios 的原始碼,超時後, 會在攔截器那裡 axios.interceptors.response 捕抓到錯誤資訊, 且 error.code = "ECONNABORTED",具體連結
// Handle timeout
request.ontimeout = function handleTimeout() {
reject(createError('timeout of ' + config.timeout + 'ms exceeded', config, 'ECONNABORTED',
request));
// Clean up request
request = null;
};
所以,我的全域性超時重新獲取的解決方案這樣的。
axios.interceptors.response.use(function(response){
....
}, function(error){
var originalRequest = error.config;
if(error.code == 'ECONNABORTED' && error.message.indexOf('timeout')!=-1 && !originalRequest._retry){
originalRequest._retry = true
return axios.request(originalRequest);
}
});
這個方法,也可以實現得新請求,但有兩個問題,1 是它只重新請求 1 次,如果再超時的話,它就停止了,不會再請求。第 2 個問題是,我在每個有資料請求的頁面那裡,做了許多操作,比如 this.$axios.get(url).then 之後操作。
完美的解決方法
以 AOP 程式設計方式,我需要的是一個 超時重新請求的全域性功能, 要在 axios.Interceptors 下功夫,在 github 的 axios 的 issue 找了別人的一些解決方法,終於找到了一個完美解決方案,就是下面這個。
https://github.com/axios/axios/issues/164#issuecomment-327837467
//在 main.js 設定全域性的請求次數,請求的間隙
axios.defaults.retry = 4;
axios.defaults.retryDelay = 1000;
axios.interceptors.response.use(undefined, function axiosRetryInterceptor(err) {
var config = err.config;
// If config does not exist or the retry option is not set, reject
if(!config || !config.retry) return Promise.reject(err);
// Set the variable for keeping track of the retry count
config.__retryCount = config.__retryCount || 0;
// Check if we've maxed out the total number of retries
if(config.__retryCount >= config.retry) {
// Reject with the error
return Promise.reject(err);
}
// Increase the retry count
config.__retryCount += 1;
// Create new promise to handle exponential backoff
var backoff = new Promise(function(resolve) {
setTimeout(function() {
resolve();
}, config.retryDelay || 1);
});
// Return the promise in which recalls axios to retry the request
return backoff.then(function() {
return axios(config);
});
});
其他的那個幾十個.vue 頁面的 this.$axios 的 get 和 post 的方法根本就不需要去修改它們的程式碼。
在這個過程中,謝謝 jooger 給予大量的技術支援,這是他的個人資訊https://github.com/jo0ger,謝謝。
以下是我做的一個試驗。。把 axios.defaults.retryDelay = 500, 請求www.facebook.com
如有更好的建議,請告訴我,謝謝。
github 原始碼, 給星星的人都很美。