自從使用 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 源代碼, 給星星的人都很美。