官方文档地址:
Axios拦截器
Axios默认配置

例:

在Vue中的man.js中配置全局属性

每次请求都会携带该数据

// axios全局配置
// server
axios.defaults.baseURL = "http://127.0.0.1:8080";
// token
axios.defaults.headers.common['X-Token'] = sessionStorage.getItem("token");

在Vue中的man.js中配置响应拦截器

这里我是根据后台返回的状态码,执行相关的逻辑,该执行是在Axios的then 和catch之前。
在这中可以配置响应超时,请求次数等的逻辑处理

// 添加响应拦截器
axios.interceptors.response.use(function (r) {
  // 2xx 范围内的状态码都会触发该函数。
  // 对响应数据做点什么
  console.log("拦截响应...")
   if (r.data.code == 101) {
    ElementUI.MessageBox("您还未登录,请登录...", "请登录", {
      confirmButtonText: "确定",
    }).then(r=>{
      location.href = "/login.html";
    });
    return;
  } else if (r.data.code == 102) {
    ElementUI.MessageBox("检测到您的登录信息过期,请重新登录...", "登录过期", {
      confirmButtonText: "确定",
    }).then(r=>{
      location.href = "/login.html";
    });
  } else if (r.data.code == 103) {
    ElementUI.MessageBox("检测到您的登录信息被篡改,请重新登录...", "token失效", {
    }).then(r=>{
      location.href = "/login.html";
    });
  } else if (r.data.code == 500) {
    ElementUI.Message({
      type: "error",
      message: "系统维护中,请稍后再试...",
    });
  } else {
    return r;
  }
}, function (error) {
  // 超出 2xx 范围的状态码都会触发该函数。
  // 对响应错误做点什么
  console.log(error);
  return Promise.reject(error);
});

使用

使用Axios发送请求时:
1、由于配置了Axios的全局属性,url 中直接写请求地址;
2、执行拦截器由于是在then 和 catch之前,如果后台返回 上述配置的拦截器中的 code 为:500 ,101等转态码时,不会执行;

	/**
     * 修改数据
     */
    updata() {
      this.editEmp.deptId = this.editEmp.dept.id;
      this.axios({
        method: "post",
        url: "/staff/update",
        data: this.editEmp,
      }).then((r) => {
        if (r.data.code == 200) {
          this.dialogFormVisible = false;
          this.getAll();
          this.$message({
            type: "success",
            message: "修改成功!",
          });
        }
      });
    },
Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐