宜呗小程序--微信小程序
Lzk
2025-08-05 b7bcaf556aa2424e808b6e6426ab22df9cfe11c1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
import { baseURL } from './config.js'
 
// 创建请求实例
const request = {
  // 通用请求方法
  async request(options = {}) {
 
    let uniPlatform = uni.getSystemInfoSync().uniPlatform;
    let platform = uni.getSystemInfoSync().uniPlatform;
    let deviceOsversion = uni.getSystemInfoSync().osName+uni.getSystemInfoSync().osVersion;
    // 处理请求配置
    const config = {
      url: options.url || '',
      method: options.method || 'GET',
      header: {
        'content-type': 'application/json',
        ...options.header
      },
      data: Object.assign({uniPlatform,platform,deviceOsversion}, options.data) || {uniPlatform,platform,deviceOsversion},
      timeout: options.timeout || 60000,
    }
 
    // 添加token
    const token = uni.getStorageSync('token')
    if (token) {
      config.header.Authorization = token
    }
    try {
      // 发起请求
      const response = await uni.request({
        ...config,
        url: `${baseURL}${config.url}`
      })
      // 处理响应
      if (response.statusCode === 200) {
 
        const { code, data, msg } = response.data
        // 根据业务状态码处理
        switch (code) {
          case 200:
            return data
          default:
            uni.showToast({
              title: data || msg ,
              icon: 'none'
            })
            throw new Error(data || msg)
        }
      }
      else if (response.statusCode === 401) {
        if(!uni.getStorageSync('token')){
          uni.reLaunch({
            url: '/pages/login/index'
          })
          return
        } else {
          uni.showToast({
            title: '登录已过期,请重新登录',
            icon: 'none'
          })
          uni.removeStorageSync('token')
          setTimeout(() => {
            uni.reLaunch({
              url: '/pages/login/index'
            })
          }, 1500)
          throw new Error('登录已过期,请重新登录')
        }
 
 
      }
      else {
        uni.showToast({
          title: '网络错误',
          icon: 'none'
        })
        throw new Error('网络错误')
      }
    } catch (error) {
      throw error || '服务器错误'
    }
  },
 
  // GET请求
  get(url, data = {}, options = {}) {
    return this.request({
      url,
      method: 'GET',
      data,
      ...options
    })
  },
 
  // POST请求
  post(url, data = {}, options = {}) {
    return this.request({
      url,
      method: 'POST',
      data,
      ...options
    })
  },
}
 
export default request