axios 超时重新请求

870 阅读1分钟
//请求超时时限 设置9000毫秒
axios.defaults.timeout =  9000;
//请求次数
axios.defaults.retry = 4;
//请求的间隙
axios.defaults.retryDelay = 1000;


/*添加响应拦截器*/
axios.interceptors.response.use(function(response){
    return response;
    }, function(error){
    //请求超时的之后,抛出 error.code = ECONNABORTED的错误..错误信息是 timeout of  xxx ms exceeded
    if(error.code == 'ECONNABORTED' && error.message.indexOf('timeout')!=-1){
        var config = error.config;
        config.__retryCount = config.__retryCount || 0;
        if(config.__retryCount >= config.retry) {
        // Reject with the error
        //window.location.reload();
        return Promise.reject(error);
    }
        // Increase the retry count
        config.__retryCount += 1;
        // Create new promise to handle exponential newHttp
        var newHttp = new Promise(function(resolve) {
            setTimeout(function() {
                //console.log('resolve');
                resolve();
            }, config.retryDelay || 1);
        });
        return newHttp.then(function() {
            return axios(config);
        });
    }else{
        return Promise.reject(error);
    }
});