request.js 3.29 KB
import config from '@/config/index.js';
import store from '@/store/index.js';

const apiHost = config.apiHost;
const env = config.env;
const systemInfo = wx.getSystemInfoSync();

// 此vm参数为页面的实例,可以通过它引用vuex中的变量
module.exports = vm => {
  // 初始化请求配置
  uni.$u.http.setConfig(config => {
    /* config 为默认全局配置*/
    config.baseURL = apiHost; /* 根域名 */
    config.header = {
      'content-type': 'application/json;charset=UTF-8',
      deviceName: systemInfo.brand, // 设备品牌
      deviceModel: systemInfo.model, // 设备型号
      systemType: systemInfo.platform, // 操作系统类型
      systemVersion: systemInfo.system, // 操作系统版本
      wechatVersion: systemInfo.version, // 微信版本
      SDKVersion: systemInfo.SDKVersion, // 基础库版本
      platform: 'mp', // 当前运行平台
      env: env, //环境
    };
    return config;
  });

  // 请求拦截
  uni.$u.http.interceptors.request.use(
    config => {
      // 可使用async await 做异步操作
      if (config.custom.auth === false) {
        delete config.header['Authorization'];
      } else {
        config.header['Authorization'] = `Bearer ${vm.$store.state?.userInfo?.accessToken}`;
      }
      // config.header['Authorization'] = `Bearer 814aec36-60b1-4b47-a0fa-b909501f3e48`;
      return config;
    },
    config => {
      // 可使用async await 做异步操作
      return Promise.reject(config);
    },
  );

  // 响应拦截
  uni.$u.http.interceptors.response.use(
    response => {
      const { data = {}, statusCode, config } = response;
      const { success, message = '', businessException, errorCode } = data;
      if (config && config.interceptors === false) {
        // 请求配置不做返回拦截的情况
        return response;
      } else {
        if (success) {
          return data;
        } else {
          if (`${errorCode}` === '401') {
            console.error(`【${errorCode}】登录过期`);
            store.commit('SET_AUTHED', false);
            setTimeout(() => {
              uni.reLaunch({ url: '/pages/login/login' });
            }, 200);
            return Promise.reject(message);
          }
          if (businessException && !(config && config.custom && config.custom.toast)) {
            uni.showToast({ icon: 'none', title: message || `[${errorCode}]系统异常`, duration: 3000 });
          } else if (!(config && config.custom && config.custom.toast)) {
            if (config.toast !== false) {
              if (`${errorCode}`.substr(0, 1) === '5') {
                uni.showToast({ icon: 'none', title: `[${errorCode}]系统异常`, duration: 3000 });
              } else {
                uni.showToast({ icon: 'none', title: message || `[${errorCode}]系统异常`, duration: 3000 });
              }
            }
          }
          return Promise.reject(message);
        }
      }
    },
    response => {
      // 对响应错误做点什么 (statusCode !== 200)
      const { statusCode } = response;
      if (statusCode === 401) {
        console.error(`【${statusCode}】登录过期`);
        store.commit('SET_AUTHED', false);
        setTimeout(() => {
          uni.reLaunch({ url: '/pages/login/login' });
        }, 1200);
      }
      return Promise.reject(response);
    },
  );
};