axios.js 2.02 KB
import axios from 'axios';
import router from '@/router';
import _ from 'lodash'
import qs from 'Qs'
// import { parseQueryString } from '@/utils/tools'

axios.defaults.params = {
  f: 'voice',
};

/**
 * @description 请求拦截器
 */
axios.interceptors.request.use(
  config => {
    // const url_params = parseQueryString(location.href);
    // GET请求默认打上时间戳,避免从缓存中拿数据。
    const timestamp = config.method === 'get' ? (new Date()).valueOf() : '';
    // 上传相关接口需要屏蔽掉封装, 不能序列化数据会报错。
    if (
      config.method === 'post' &&
      (config.url.indexOf('a=upload') === -1 &&
       config.url.indexOf('upload.qiniup.com') === -1
      )
    )
    {
      // POST PHP需要修改数据格式
      config.data = qs.stringify(config.data)
    }
    // 绑定默认请求头
    config.params = _.merge(config.params, {
      timestamp,
    })
    return config;
  },
  error => {
    // 请求错误处理
    return Promise.reject(error);
  });

/**
 * @description 响应拦截器
 */
axios.interceptors.response.use(
  response => {
    // 默认显示错误提示
    response.data.show = true;
    // C/B 授权拼接头特殊标识,openid_x
    let userType = router && router.currentRoute.value.href?.indexOf('business') > 0 ? 'b' : 'c';
    if (response.data.code === 401) {
      // 特殊标识-带此标识报错不显示
      response.data.show = false;
      // 未授权跳转登录页
      // 带着上一个页面的信息, 授权完成后 返回当前页面
      router.replace({
        path: '/auth',
        query: {
          // href: router.currentRoute.value.href,
          href: location.hash,
          userType
        }
      });
    }
    // 拦截B端未登录情况
    if (response.data.msg === '老师请先登录!' || response.data.msg === '老师不存在!') {
      router.replace({
        path: '/business/login'
      });
    }
    return response;
  },
  error => {
    return Promise.reject(error);
  });

export default axios;