axios设置请求超时时间与超时取消请求

一、设置超时时间,超时取消请求

场景:调用第三方接口不太稳定,需要设置超时时间,超时取消请求并提示连接超时

使用cancelToken参数,axios自带cancelToken参数

1.axios请求外部

const CancelToken = axios.CancelToken;
    let cancel;
    let timer = setTimeout(() => {
        cancel();
        this.$message.error("连接超时,请检查网络!")
    }, 10000);

2.axios请求内部

this.axios({
     method: "post",
     url,
     data,
     cancelToken: new CancelToken(function executor(c) {
         cancel = c;
     }),
 })
 .then((response) => {
     clearTimeout(timer);
     if (!response.data.hasError) {
         this.$message.success("数据获取成功!");
         const results = response.data.result;
     } else {
         this.$message.error("数据获取失败!");
     }
 })
 .catch((error) => {
     clearTimeout(timer);
     if (error.response) {
         this.$message.error("数据获取失败!");
     }
 });

注意: 可以使用同一个 cancel token 取消多个请求

二、设置超时时间,超时重新请求

配置axios拦截器

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

使用的时候,

1.retry - 第一次请求失败后重试请求的次数。
2.retryDelay -在失败请求之间等待的毫秒数(默认为1)。

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

 参考:https://www.jianshu.com/p/e58ff85b2a91

原文地址:https://www.cnblogs.com/younghxp/p/14307156.html