axios拦截respose

95 阅读1分钟
  1. axios拦截器中给HTTP统一添加Authorization信息

 // /src/api/config.js
   axios.interceptors.request.use(
     config => {
       const token = localStorage.getItem('SONG_EAGLE_TOKEN');
       if (token) {
         // Bearer是JWT的认证头部信息
         config.headers.common['Authorization'] = 'Bearer ' + token;
       }
       return config;
     },
     error => {
       return Promise.reject(error);
     }
   );
   

4. axios拦截器在接收到HTTP返回时统一处理返回状态


   


`// /src/main.js
   axios.interceptors.response.use(
     response => {
       return response;
     },
     error => {
       if (error.response.status === 401) {
         Vue.prototype.$msgBox.showMsgBox({
           title: '错误提示',
           content: '您的登录信息已失效,请重新登录',
           isShowCancelBtn: false
         }).then((val) => {
           router.push('/login');
         }).catch(() => {
           console.log('cancel');
         });
       } else {
         Vue.prototype.$message.showMessage({
           type: 'error',
           content: '系统出现错误'
         });
       }
       return Promise.reject(error);
     }
   );`