vue使用axios.interceptors.response响应拦截器。实现报错接口的重新加载,弹框报错点击按钮自动加载。

axios.interceptors.response响应拦截器

axios.interceptors.response.use(function (res) {
//这里是响应成功执行的代码
}, function axiosRetryInterceptor(err) {
//这里是响应失败执行的代码
});

我要实现的功能介绍

当接口请求超时,让报错接口默认再次加载一遍,第二遍还是请求超时之后,弹出弹框,提示请求超时,请重新加载,点击按钮重新加载,再次加载报错接口。关闭弹框不加载接口:

main.js

import ElementUI from 'element-ui'
Vue.use(ElementUI)
//使用了ElementUI.Notification的弹框,必须引入ElementUI
axios.interceptors.response.use(function (res) {
    // console.log(res);
    var qiandizhi = window.location.href
    if (res.data.code == '201' || res.data.code == '801' || res.data.code == '802' || res.data.code == '803') {
        if (res.data.msg != 'token 无效' && res.data.msg != 'token 为空' && res.data.msg) {
            ElementUI.Notification({
                dangerouslyUseHTMLString: true,
                message:
                    '<div class="tishi-div"><i class="tishi-icon"></i>' + res.data.msg + '</div>',
                position: "bottom-right",
                showClose: false,
                duration: 3000,
            });
        }
        router.replace({
            path: '/login',
            query: { 'qianurl': qiandizhi}
        })
        return false;
    } else if ( res.data.code == '501' || res.data.code == '605') {
        if (res.config.tanBlo) {
            return ElementUI.MessageBox({
                title: '提示',
                message: '<div style="display: flex;align-items: center;"><img src="./static/img/yichang.png" style="margin-right: 0.1429rem;" /><div style="color: #333333;font-size: 0.1905rem;">加载超时,请稍后重试</div></div>',
                dangerouslyUseHTMLString: true,
                confirmButtonText: "重新加载"
            }).then(() => {
                return axios(res.config)
            });
        }
    } else if (res.data.code != 200 && res.data.code != '1' && res.config.url != '/zyzx/navigation/base') {
        if (res.data.msg != null && res.data.msg != "null" && res.data.msg) {
            ElementUI.Notification({
                dangerouslyUseHTMLString: true,
                message:
                '<div class="tishi-div"><i class="tishi-icon"></i>' + res.data.msg + '</div>',
                position: "bottom-right",
                showClose: false,
                duration: 3000,
            });
        }
    }
    return res;
}, 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) {
        if (err.response.status == 500 && config.tanBlo) {
            return ElementUI.MessageBox({
                title: '提示',
                message: '<div style="display: flex;align-items: center;"><img src="./static/img/yichang.png" style="margin-right: 0.1429rem;" /><div style="color: #333333;font-size: 0.1905rem;">加载超时,请稍后重试</div></div>',
                dangerouslyUseHTMLString: true,
                confirmButtonText: "重新加载"
            }).then(() => {
                return axios(config);
            }).catch(() => {
            });
            
        }
        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:加载接口的时间间隔
tanBlo: 自定义的参数,用来判断是否显示报错弹框,再次重新加载

组件中的使用

this.http.post("接口", this.dataParams, {retry: 1, retryDelay: 1000, tanBlo: true,
        cancelToken: new this.http.CancelToken(function executor(c) {
            that.source = c;
        })
      }).then(res => {}).catch(err => {});
Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐