request.js 3.33 KB
/*
 * @Date: 2022-09-19 14:11:06
 * @LastEditors: hookehuyr hookehuyr@gmail.com
 * @LastEditTime: 2025-07-01 11:17:49
 * @FilePath: /xyxBooking-weapp/src/utils/request.js
 * @Description: 简单axios封装,后续按实际处理
 */
// import axios from 'axios'
import axios from 'axios-miniprogram';
import Taro from '@tarojs/taro'
// import { strExist } from './tools'
// import qs from 'Qs'
import { mainStore } from '@/stores/main'

// import { ProgressStart, ProgressEnd } from '@/components/axios-progress/progress';
// import store from '@/store'
// import { getToken } from '@/utils/auth'
import BASE_URL from './config';

/**
 * 获取sessionid的工具函数
 * @returns {string|null} sessionid或null
 */
const getSessionId = () => {
  try {
    return Taro.getStorageSync("sessionid") || null;
  } catch (error) {
    console.error('获取sessionid失败:', error);
    return null;
  }
};

// create an axios instance
const service = axios.create({
  baseURL: BASE_URL, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000, // request timeout
})

service.defaults.params = {
  f: 'reserve',
  client_name: '智慧西园寺',
};

// request interceptor
service.interceptors.request.use(
  config => {
    // console.warn(config)
    // console.warn(store)

    /**
     * 动态获取sessionid并设置到请求头
     * 确保每个请求都带上最新的sessionid
     */
    const sessionid = getSessionId();
    if (sessionid) {
      config.headers.cookie = sessionid;
    }
    
    // 增加时间戳
    if (config.method === 'get') {
        config.params = { ...config.params, timestamp: (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;
    return config
  },
  error => {
    // do something with request error
    console.error(error, 'err') // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
   */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    const res = response.data
    
    // 401 未授权处理
    if (res.code === 401) {
        // 跳转到授权页
        // 避免死循环,如果已经在 auth 页则不跳
        const pages = Taro.getCurrentPages();
        const currentPage = pages[pages.length - 1];
        if (currentPage && currentPage.route !== 'pages/auth/index') {
            Taro.navigateTo({
                url: '/pages/auth/index'
            });
        }
        return response; // 返回 response 以便业务代码处理(或者这里 reject)
    }

    if (['预约ID不存在'].includes(res.msg)) {
      res.show = false;
    }
    
    return response
  },
  error => {
    console.log('err' + error) // for debug
    // Taro.showToast({
    //   title: error.message,
    //   icon: 'none',
    //   duration: 2000
    // })
    return Promise.reject(error)
  }
)

export default service