//捕获401
// http request 拦截器 
axios.interceptors.request.use(
  config => {
    const token = localStorage.getItem('token')
    if (token) { // 判断是否存在token,如果存在的话,则每个http header都加上token
      // console.log(token)
      config.headers.Authorization = token
    }
    return config;
  },
  err => {
    return Promise.reject(err);
  });

// http response 拦截器
axios.interceptors.response.use(
  response => {
    return response;
  },
  error => {
    if (error.response) {
      switch (error.response.status) {
        case 401:
          // 返回 401 清除token信息并跳转到登录页面
          router.replace({
            path: '/login',
            query: {
              redirect: router.currentRoute.fullPath
            }
          })
      }
    }
    return Promise.reject(error.response.data) // 返回接口返回的错误信息
  });
View Code
login.vue
localStorage.setItem('token', "Bearer " + res.data.data.Token)
View Code

参考文章:https://www.cnblogs.com/WNpursue/p/11194196.html

01-15 12:59