[轉]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",具體鏈接

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

 

轉自: https://javascript.ctolib.com/ssttm169-use-axios-well.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM