vue axios請求超時的正確處理方法
自從使用Vue2之后,就使用官方推薦的axios的插件來調(diào)用API,在使用過程中,如果服務器或者網(wǎng)絡不穩(wěn)定掉包了, 你們該如何處理呢? 下面我給你們分享一下我的經(jīng)歷。
具體原因
最近公司在做一個項目, 服務端數(shù)據(jù)接口用的是Php輸出的API, 有時候在調(diào)用的過程中會失敗, 在谷歌瀏覽器里邊顯示Provisional headers are shown。

按照搜索引擎給出來的解決方案,解決不了我的問題.
最近在研究AOP這個開發(fā)編程的概念,axios開發(fā)說明里邊提到的欄截器(axios.Interceptors)應該是這種機制,降低代碼耦合度,提高程序的可重用性,同時提高了開發(fā)的效率。
帶坑的解決方案一
我的經(jīng)驗有限,覺得唯一能做的,就是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);
});
這個欄截器作用是 如果在請求超時之后,欄截器可以捕抓到信息,然后再進行下一步操作,也就是我想要用 重新請求。
這里是相關的頁面數(shù)據(jù)請求。
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的功能, 經(jīng)過測試是可以實現(xiàn)重新請求的功功能, 雖然能夠?qū)崿F(xiàn) 超時重新請求的功能,但很麻煩,需要每一個請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);
}
});
這個方法,也可以實現(xiàn)得新請求,但有兩個問題,1是它只重新請求1次,如果再超時的話,它就停止了,不會再請求。第2個問題是,我在每個有數(shù)據(jù)請求的頁面那里,做了許多操作,比如 this.$axios.get(url).then之后操作。
完美的解決方法
以AOP編程方式,我需要的是一個 超時重新請求的全局功能, 要在axios.Interceptors下功夫,在github的axios的issue找了別人的一些解決方法,終于找到了一個完美解決方案,就是下面這個。
https://github.com/axios/axios/issues/164#issuecomment-327837467
//在main.js設置全局的請求次數(shù),請求的間隙
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基本用法
vue更新到2.0之后,作者就宣告不再對vue-resource更新,而是推薦的axios,前一段時間用了一下,現(xiàn)在說一下它的基本用法。
首先就是引入axios,如果你使用es6,只需要安裝axios模塊之后
import axios from 'axios'; //安裝方法 npm install axios //或 bower install axios
當然也可以用script引入
<script src=">
axios提供了一下幾種請求方式
axios.request(config) axios.get(url[, config]) axios.delete(url[, config]) axios.head(url[, config]) axios.post(url[, data[, config]]) axios.put(url[, data[, config]]) axios.patch(url[, data[, config]])
這里的config是對一些基本信息的配置,比如請求頭,baseURL,當然這里提供了一些比較方便配置項
//config
import Qs from 'qs'
{
//請求的接口,在請求的時候,如axios.get(url,config);這里的url會覆蓋掉config中的url
url: '/user',
// 請求方法同上
method: 'get', // default
// 基礎url前綴
baseURL: 'https://some-domain.com/api/',
transformRequest: [function (data) {
// 這里可以在發(fā)送請求之前對請求數(shù)據(jù)做處理,比如form-data格式化等,這里可以使用開頭引入的Qs(這個模塊在安裝axios的時候就已經(jīng)安裝了,不需要另外安裝)
data = Qs.stringify({});
return data;
}],
transformResponse: [function (data) {
// 這里提前處理返回的數(shù)據(jù)
return data;
}],
// 請求頭信息
headers: {'X-Requested-With': 'XMLHttpRequest'},
//parameter參數(shù)
params: {
ID: 12345
},
//post參數(shù),使用axios.post(url,{},config);如果沒有額外的也必須要用一個空對象,否則會報錯
data: {
firstName: 'Fred'
},
//設置超時時間
timeout: 1000,
//返回數(shù)據(jù)類型
responseType: 'json', // default
}
有了配置文件,我們就可以減少很多額外的處理代碼也更優(yōu)美,直接使用
axios.post(url,{},config)
.then(function(res){
console.log(res);
})
.catch(function(err){
console.log(err);
})
//axios請求返回的也是一個promise,跟蹤錯誤只需要在最后加一個catch就可以了。
//下面是關于同時發(fā)起多個請求時的處理
axios.all([get1(), get2()])
.then(axios.spread(function (res1, res2) {
// 只有兩個請求都完成才會成功,否則會被catch捕獲
}));
最后還是說一下配置項,上面講的是額外配置,如果你不想另外寫也可以直接配置全局
axios.defaults.baseURL = 'https://api.example.com';
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
//當然還可以這么配置
var instance = axios.create({
baseURL: 'https://api.example.com'
});
本文只是介紹基本的用法,詳細看官方文檔https://github.com/axios
我寫的兩個例子:
使用vue2.0+mintUI+axios+vue-router: https://github.com/Stevenzwzhai/vue-mobile-application
使用vue2.0+elementUI+axios+vue-router: https://github.com/Stevenzwzhai/vue2.0-elementUI-axios-vueRouter, 之前由于沒做后端接口,所以運行沒數(shù)據(jù),現(xiàn)在加了mockjs來返回一些數(shù)據(jù),以便于參考。
總結(jié)
以上所述是小編給大家介紹的axios請求超時,設置重新請求的完美解決方法,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!

