request.js 4.03 KB
import base from "@/config/baseUrl";
import store from "@/store";
import { judgeLogin } from "@/config/login";

// 初始化请求配置
uni.$u.http.setConfig((config) => {
  const token =
    store.state.userInfo.isToken ||
    uni.getStorageSync("userInfo").isToken ||
    undefined;
  // #ifdef H5
  window.sessionStorage.getItem("userInfo").isToken;
  // #endif
  /* config 为默认全局配置*/
  config.baseURL = base.baseUrl; /* 根域名 */
  config.header = {
    "Content-Type": "application/json",
    Authorization: "Bearer " + token,
  };
  config.custom = {
    load: true, //是否显示加载动画
    isFactory: true, //true:返回的数据成功只返回data  false:返回response
    catch: true, //默认数据返回不成功进入catch返回
    auth: true, //token
  };
  return config;
});

// 请求拦截
uni.$u.http.interceptors.request.use(
  (config) => {
    // 可使用async await 做异步操作
    // 初始化请求拦截器时,会执行此方法,此时data为undefined,赋予默认{}
    config.data = config.data || {};
    // 根据custom参数中配置的是否需要token,添加对应的请求头
    if (config?.custom?.auth) {
      config.header.Authorization =
        "Bearer " + store.state.userInfo.isToken ||
        uni.getStorageSync("userInfo").isToken ||
        undefined;
    }
    // console.log("请求开始", config);
    if (config?.custom?.load) {
      //打开加载动画
      store.commit("setLoadingShow", true);
    }

    return config;
  },
  (config) => {
    // 可使用async await 做异步操作
    return Promise.reject(config);
  }
);

// 响应拦截
uni.$u.http.interceptors.response.use(
  (response) => {
    /* 对响应成功做点什么 可使用async await 做异步操作*/
    // 关闭加载动画
    store.commit("setLoadingShow", false);
    const data = response.data;
    // 自定义参数
    const custom = response.config?.custom;
    // code:  200、请求成功 其他,没有更多参数 401、被迫下线重新登录、
    if (response.statusCode == 200) {
      return Promise.resolve(data);
      // if (!custom.isFactory) {
      // 	return Promise.reject(response.data)
      // } else {
      // 	return data.data === undefined ? {} :  Promise.reject(response.data)
      // }
    } else if (response.statusCode == 401) {
      //被迫下线重新登录
      // 清空登录信息
      store.commit("emptyUserInfo");
      // 20秒节流,弹窗登录
      uni.$u.throttle(judgeLogin(), 20000);
      return new Promise(() => {});
    } else {
      // 如果没有显式定义custom的toast参数为false的话,默认对报错进行toast弹出提示
      if (custom.toast !== false) {
        uni.$u.toast(data.message || data.msg);
      }
      // 如果需要catch返回,则进行reject
      if (custom?.catch) {
        return Promise.reject(data);
      } else {
        // 否则返回一个pending中的promise,请求不会进入catch中
        return new Promise(() => {});
      }
    }
  },
  (response) => {
    // 关闭加载动画
    store.commit("setLoadingShow", false);
    // 对响应错误做点什么 (statusCode !== 200)
    let errorData = "请检查网络或服务器";
    let message = response.data?.message || response?.errMsg;
    if (message == "request:fail url not in domain list") {
      errorData = "检查请求域名是否添加了域名白名单";
    } else if (message == "request:fail timeout") {
      errorData = "请求超时:请检查网络";
    } else if (message == "Token has expired") {
      errorData = "Token失效,请重新登录";
      uni.reLaunch({
        url: "/publicLoginSubPage/public/login",
      });
      store.commit("emptyUserInfo");
    } else if (message == "Invalid username or password") {
      errorData = "用户名或者密码无效";
      uni.reLaunch({
        url: "/publicLoginSubPage/public/login",
      });
      store.commit("emptyUserInfo");
    } else {
      errorData = message || "请检查网络或服务器";
    }
    uni.$u.toast(errorData);
    return Promise.reject(response);
  }
);