axios.js 3.54 KB
/*
 * @Author: hookehuyr hookehuyr@gmail.com
 * @Date: 2022-05-28 10:17:40
 * @LastEditors: hookehuyr hookehuyr@gmail.com
 * @LastEditTime: 2026-01-24 12:41:18
 * @FilePath: /xysBooking/src/utils/axios.js
 * @Description: axios 实例与拦截器(统一参数、统一鉴权跳转、统一错误提示入口)
 */
import axios from 'axios';
import router from '@/router';
// import qs from 'Qs'
// import { strExist } from '@/utils/tools'
// import { parseQueryString } from '@/utils/tools'

// 设置所有请求默认携带的公共参数
axios.defaults.params = {
  f: 'reserve',
  client_name: '智慧西园寺',
};

/**
 * 请求拦截器
 * - GET 默认追加时间戳,避免浏览器/中间层缓存导致数据不更新
 * - 统一补齐 config.params,保证公共参数与业务参数可以并存
 * @param {import('axios').InternalAxiosRequestConfig} config axios 请求配置
 * @returns {import('axios').InternalAxiosRequestConfig} 处理后的请求配置
 */
axios.interceptors.request.use(
  config => {
    // const url_params = parseQueryString(location.href);
    // GET请求默认打上时间戳,避免从缓存中拿数据。
    const timestamp = config.method === 'get' ? (new Date()).valueOf() : '';
    /**
     * POST PHP需要修改数据格式
     * 序列化POST请求时需要屏蔽上传相关接口,上传相关接口序列化后报错
     */
    // config.data = config.method === 'post' && !strExist(['a=upload', 'upload.qiniup.com'], config.url) ? qs.stringify(config.data) : config.data;
    // 绑定默认请求头
    config.params = { ...config.params, timestamp }
    // config.params = config.method === 'get' && !strExist(['a=session'], config.url) ? { ...config.params, timestamp } : {};
    return config;
  },
  error => {
    // 请求错误处理(如:参数序列化异常、网络层拦截等)
    return Promise.reject(error);
  });

/**
 * 响应拦截器
 * - 约定后端返回 { code, data, msg, show } 结构
 * - code === 401 时,进行授权页跳转(避免未授权接口一直报错)
 * - 部分业务错误提示需要静默(show === false 或命中特定 msg)
 * @param {import('axios').AxiosResponse} response axios 响应对象
 * @returns {import('axios').AxiosResponse} 原样返回响应(由上层 fn 统一处理 code/msg)
 */
axios.interceptors.response.use(
  response => {
    // // 默认显示错误提示
    // response.data.show = true;
    // // 判断微信授权状态,进入页面时未授权需要授权跳转
    // // C/B 授权拼接头特殊标识,openid_x
    // let prefixAPI = router?.currentRoute.value.href?.indexOf('business') > 0 ? 'b' : 'c';
    if (response.data.code === 401) {
      // 未授权时不弹 Toast,统一跳转到授权页
      response.data.show = false;
      const request_params = response?.config?.params || {};
      const is_redeem_admin = request_params?.f === 'reserve_admin';
      const current_path = router?.currentRoute?.value?.path || '';
      if (!is_redeem_admin && current_path !== '/auth') {
        router.replace({ path: '/auth', query: { href: location.hash } });
      }
    }
    if (['预约ID不存在'].includes(response.data.msg)) {
      // 这类错误属于流程中“可预期异常”,不提示用户,交给页面自行兜底
      response.data.show = false;
    }
    // // 拦截B端未登录情况
    // if (['老师请先登录!', '老师不存在!'].includes(response.data.msg)) { router.replace({ path: '/business/login' }); }
    return response;
  },
  error => {
    return Promise.reject(error);
  });

export default axios;