axios 请求超时,设置重新请求

axios 配置

axios.defaults.timeout = 15000;           //超时时间
axios.defaults.retry = 3;                 //请求次数
axios.defaults.retryDelay = 1000;         //请求间隙
// http response 拦截器
axios.interceptors.response.use(
    response => {
       //登录过期
        if(response.data.errorCode == -1) {
            store.commit('logout', this);
        }
        return response;
    },
    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);
            });
        
    });
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容