车间能级提升-智能设备管理系统
zhuguifei
2025-04-21 0f5bd3db43a7ea07d3373b38bd24126544de5e2f
eims-ui-mobile/src/utils/http.ts
@@ -2,6 +2,9 @@
import { useUserStore, useAccessStore } from '@/store'
export const http = <T>(options: CustomRequestOptions) => {
  uni.showLoading({
    title: '加载中',
  })
  // 1. 返回 Promise 对象
  return new Promise<IResData<T>>((resolve, reject) => {
    uni.request({
@@ -12,11 +15,26 @@
      // #endif
      // 响应成功
      success(res) {
        uni.hideLoading()
        // 状态码 2xx,参考 axios 的设计
        if (res.statusCode >= 200 && res.statusCode < 300) {
          // 2.1 提取核心数据 res.data
          if ((res.data as IResData<T>).code === 200) {
            resolve(((res.data as IResData<T>).data || res.data) as IResData<T>)
          } else if ((res.data as IResData<T>).code === 401) {
            uni.showToast({
              icon: 'none',
              title: '登录超时,请重新登录!',
            })
            // 401错误  -> 清理用户信息,跳转到登录页
            useAccessStore().clearAccessInfo()
            useUserStore().clearUserInfo()
            const loginRoute = '/pages/login/index'
            // 重新登录后返回页面
            const url = '/pages/home/index'
            const redirectRoute = `${loginRoute}?redirect=${encodeURIComponent(url)}`
            uni.navigateTo({ url: redirectRoute })
            reject(res)
          } else {
            uni.showToast({
              icon: 'none',
@@ -46,6 +64,7 @@
          title: '网络错误,换个网络试试',
        })
        reject(err)
        uni.hideLoading()
      },
    })
  })
@@ -85,5 +104,19 @@
  })
}
export const httpPut = <T>(
  url: string,
  data?: Record<string, any>,
  query?: Record<string, any>,
) => {
  return http<T>({
    url,
    query,
    data,
    method: 'PUT',
  })
}
http.get = httpGet
http.post = httpPost
http.put = httpPut