axios处理请求超时重新请求

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_34664239/article/details/90515598

添加响应拦截器

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);
    });
});

使用方式:在参数中添加两个字段retry次数,retryDelay间隔时长

axios.get('/some/endpoint', { retry: 5, retryDelay: 1000 })
    .then(function(res) {
        console.log('success', res.data);
    })
    .catch(function(err) {
        console.log('failed', err);
    });

axios相关文档:
看云axios使用说明:https://www.kancloud.cn/yunye/axios/234845
axios,github问题164: https://github.com/axios/axios/issues/164
拦截器的应用实例:https://www.jianshu.com/p/ff8541e0976a

猜你喜欢

转载自blog.csdn.net/qq_34664239/article/details/90515598
今日推荐