马宇豪
2025-05-14 c533e456515a9af7fc4bca098f7cf48b9a660e21
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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
// utils/http.js
const BASE_URL = 'http://192.168.2.58:8083'; // 替换为你的API基础地址
 
// 全局配置
const config = {
  showToast: true,       // 默认显示Toast提示
  autoToken: true,       // 自动携带token
  contentType: 'application/json' // 默认Content-Type
};
 
/**
 * 核心请求函数
 * @param {object} options 请求配置
 * @returns {Promise}
 */
function service(options = {}) {
  // 合并配置
  options.url = `${BASE_URL}${options.url}`;
  
  // 配置请求头
  const token = wx.getStorageSync('tk');
  options.header = {
    'Content-Type': options.header || config.contentType,
    'Authorization': config.autoToken ? token : ''
  };
 
  return new Promise((resolve, reject) => {
    // 成功回调
    options.success = (res) => {
      // 处理403/401未授权情况
      if (res.data.code === 403 || res.data.code === 401) {
        showToast(res.data.message || '登录已过期');
        clearStorageAndRedirect();
        reject(res.data);
      } 
      // 处理200成功情况
      else if (res.data.code === 200) {
        if (res.data.msg === '您点击太快了,请稍后尝试') {
          showToast(res.data.message || '操作过于频繁');
        }
        resolve(res.data);
      }
      // 其他情况直接返回数据
      else {
        resolve(res.data);
      }
    };
 
    // 失败回调
    options.fail = (err) => {
      showToast('服务响应失败');
      clearStorageAndRedirect();
      reject(err);
    };
 
    // 发起请求
    wx.request(options);
  });
}
 
/**
 * 显示Toast提示
 * @param {string} title 提示内容
 */
function showToast(title) {
  if (config.showToast) {
    wx.showToast({
      title: title,
      icon: 'none',
      duration: 2000
    });
  }
}
 
/**
 * 清除缓存并跳转到首页
 */
function clearStorageAndRedirect() {
  wx.clearStorageSync();
  setTimeout(() => {
    wx.reLaunch({
      url: '/pages/index/index' // 替换为你的登录页路径
    });
  }, 2000);
}
 
// ===== 快捷方法 =====
module.exports = {
  // GET请求
  get: (url, data, options = {}) => {
    return service({
      url,
      data,
      method: 'GET',
      ...options
    });
  },
  
  // POST请求
  post: (url, data, options = {}) => {
    return service({
      url,
      data,
      method: 'POST',
      ...options
    });
  },
  
  // PUT请求
  put: (url, data, options = {}) => {
    return service({
      url,
      data,
      method: 'PUT',
      ...options
    });
  },
  
  // DELETE请求
  delete: (url, data, options = {}) => {
    return service({
      url,
      data,
      method: 'DELETE',
      ...options
    });
  },
  
  // 文件上传
  upload: (url, filePath, formData = {}, options = {}) => {
    return new Promise((resolve, reject) => {
      wx.uploadFile({
        url: `${BASE_URL}${url}`,
        filePath,
        name: 'file',
        formData,
        header: {
          'Authorization': wx.getStorageSync('tk'),
          ...options.header
        },
        success: (res) => {
          try {
            const data = JSON.parse(res.data);
            if (data.code === 200) {
              resolve(data);
            } else {
              reject(data);
            }
          } catch (e) {
            reject(new Error('上传失败'));
          }
        },
        fail: (err) => {
          showToast('上传失败');
          reject(err);
        }
      });
    });
  },
  
  // 全局配置修改
  setConfig: (newConfig) => {
    Object.assign(config, newConfig);
  }
};