当前位置:   article > 正文

axios发送请求,全局处理异常_axios的complete

axios的complete

之前用ajax的时候,jquery中的ajax处理全局异常,通过设置ajaxSetup方法:

$.ajaxSetup({
        headers: {'Authorization': header},   //添加请求头
        complete:function(xhr,data){    //执行完success或者error方法后均要执行这个complete函数,可以用来捕获异常
            if(xhr.status == 401){
               console.log("身份过期!");
            }
            if(xhr.responseJSON != undefined){
                if((xhr.responseJSON.code == 1) && (xhr.responseJSON.msg == "不允许访问")){
                    console.log("没有此操作权限!");
                }
            }

        }
    });
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

但是在axios实现树形菜单的时候,用到了菜单的增加、编辑与删除,因此用到了vue,但是也需要对异常请求进行全局处理,代码如下:

axios.interceptors.response.use(function (response) {
    return response;
}, function (error) {
    if (error.response) {
        if(error.response.data.code == 1){
            
        }
        if(error.response.data.code == 1 && error.response.data.msg == "不允许访问"){
            /
        }
        if(error.response.status == "401"){
            /
        }
    } else if (error.request) {
        console.log(error.request);
    } else {
        console.log('Error', error.message);
    }
});
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19

采用上述设置很简便哦,否则每个请求都要写一遍,不仅容易产生代码冗余,而且不利于维护。。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/article/detail/57052
推荐阅读
相关标签
  

闽ICP备14008679号