axios請求超時,設定重新請求的完美解決方法

Tom_Tan發表於2019-03-04

自從使用Vue2之後,就使用官方推薦的axios的外掛來呼叫API,在使用過程中,如果伺服器或者網路不穩定掉包了, 你們該如何處理呢? 下面我給你們分享一下我的經歷。

具體原因

最近公司在做一個專案, 服務端資料介面用的是Php輸出的API, 有時候在呼叫的過程中會失敗, 在谷歌瀏覽器裡邊顯示Provisional headers are shown。

axios請求超時,設定重新請求的完美解決方法

按照搜尋引擎給出來的解決方案,解決不了我的問題.


最近在研究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的錯誤。

axios請求超時,設定重新請求的完美解決方法

在 catch那裡,它返回的是error.request錯誤,所以就在這裡做 retry的功能, 經過測試是可以實現重新請求的功功能, 雖然能夠實現 超時重新請求的功能,但很麻煩,需要每一個請API的頁面裡邊要設定重新請求。

axios請求超時,設定重新請求的完美解決方法

看上面,我這個專案有幾十個.vue 檔案,如果每個頁面都要去設定超時重新請求的功能,那我要瘋掉的.

而且這個機制還有一個嚴重的bug,就是被請求的連結失效或其他原因造成無法正常訪問的時候,這個機制失效了,它不會等待我設定的6秒,而且一直在刷,一秒種請求幾十次,很容易就把伺服器搞垮了,請看下圖, 一眨眼的功能,它就請求了146次。

axios請求超時,設定重新請求的完美解決方法

帶坑的解決方案二

研究了axios的原始碼,超時後, 會在攔截器那裡 axios.interceptors.response 捕抓到錯誤資訊, 且 error.code = "ECONNABORTED",具體連結

https://github.com/axios/axios/blob/26b06391f831ef98606ec0ed406d2be1742e9850/lib/adapters/xhr.js#L95-L101

    // 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

axios請求超時,設定重新請求的完美解決方法

如有更好的建議,請告訴我,謝謝。

github原始碼

相關文章