之前用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("沒有此操作權限!");
}
}
}
});
但是在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);
}
});
採用上述設置很簡便哦,否則每個請求都要寫一遍,不僅容易產生代碼冗餘,而且不利於維護。。