axios拦截器加autho验证,接口失效后重新请求的写法

//request拦截
service.interceptors.request.use(
  request => {
    let { current } = router.history;
    if (
      store.getters["userStore/getToken"] &&
      current.name !== "Login" &&
      request.url != "/login/token/refresh"
    ) {
      //非登陆界面并且不是调用刷新接口并且本地要有token才可以加autho验证
      request.headers.Authorization = `Bearer ${
        store.getters["userStore/getToken"]
      }`;
    }
    return request;
  },
  error => {
    console.error(error);
    return error;
  }
);

//response拦截
service.interceptors.response.use(
  response => {
    return response;
  },
  async error => {
    try {
      if (error && error.response) {
        // debugger;
        switch (error.response.status) {
          case 401:
            // 返回 401 清除token信息并跳转到登录页面也可以用这个逻辑
            let refreshToken = store.getters["userStore/getParamRefreshToken"];
            let { data } = await post("login/token/refresh", {
              refreshToken
            });
            if (data.code === 200) {
              //刷新token成功后,获取新的token,覆盖旧的token,然后返回到报错的页面刷新掉
              store.commit("userStore/setParamToken", data.result.access_token);
              //就是重新调用接口获取数据
              var backoff = new Promise(resolve => {
                resolve();
              });
              return backoff.then(r => {
                return service(error.config);
              });
              // window.location.reload();
            } else {
              //refreshtoken失效的话,就直接到登陆页面
              router.push("/login");
            }
            return error;
          default:
            console.error(error);
            return error;
        }
      } else {
        console.error(error);
        return error;
      }
    } catch (error) {
      console.error(error);
    }
  }
);

 

axios拦截器加autho验证,接口失效后重新请求的写法

上一篇:使用动态路由协议联通全网


下一篇:JsonMapper json字符串转对象