管灌系统农户端微信小程序(嘉峪关应用)
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
166
167
168
169
170
// 引入状态码statusCode
const statusCode = require('./statusCode')
// 定义请求路径, BASEURL: 普通请求API; CBASEURL: 中台API,不使用中台可不引入CBASEURL
const config = require('./config')
// 定义默认参数
const defaultOptions = {
  data: {},
  ignoreToken: false,
  form: false,
}
/**
 * 发送请求
 * @params
 * method: <String> 请求方式: POST/GET
 * url: <String> 请求路径
 * data: <Object> 请求参数
 * ignoreToken: <Boolean> 是否忽略token验证
 * form: <Boolean> 是否使用formData请求
 */
function request(options) {
  // let _options = Object.assign(defaultOptions, options)
  let _options = {
    ...defaultOptions,
    ...options
  }
  let {
    method,
    url,
    data,
    ignoreToken,
    form,
    isShowLoding,
    timeout,
    header,
    useParams
  } = _options
 
  // 检查url是否为undefined
  if (!url) {
    console.error('请求URL不能为空');
    return Promise.reject(new Error('请求URL不能为空'));
  }
 
  const app = getApp()
  // 设置请求头
  if (form) {
    header = {
      'content-type': 'application/x-www-form-urlencoded'
    }
  } else {
    header = {
      'content-type': 'application/json' //自定义请求头信息
    }
  }
  if (!timeout) {
    timeout = 60000
  }
 
  if (!ignoreToken) {
    // 从全局变量中获取token
    let token = app.globalData.token
    header.Authorization = `Bearer ${token}`
  }
  header.tag = app.globalData.tag;
  header.appId = app.globalData.AppID;
  return new Promise((resolve, reject) => {
    // 获取最新的 BASEURL
    let currentBaseUrl = app.globalData.baseUrl || config.BASEURL;
 
    console.log("url:" + currentBaseUrl + url);
    if (isShowLoding) {
      wx.showLoading({
        title: '通信中...', // 加载动画标题
        mask: true, // 是否显示透明蒙层,防止触摸穿透
      });
    }
    let myUrl;
    if (url.startsWith('http')) {
      myUrl = url;
    } else {
      myUrl = currentBaseUrl + url;
    }
    // 如果 useParams 为 true,拼接查询参数
    if (useParams && data) {
      const queryString = objToQueryString(data); // 使用上面定义的函数
      myUrl += `?${queryString}`; // 拼接查询字符串
      data = {}; // 请求体数据设为空
    }
    wx.request({
      url: myUrl,
      data,
      header,
      method,
      timeout: timeout,
      success: (res) => {
        let {
          statusCode: code
        } = res
        console.log("success  statusCode:" + code);
        if (isShowLoding) {
          wx.hideLoading(); // 隐藏加载动画
        }
        if (code === statusCode.SUCCESS) {
          if (res.data.code !== "0001") {
            // 统一处理请求错误
            // showToast(res.data.errorMsg)
            reject(res.data)
            return
          }
          resolve(res.data)
        } else if (code === statusCode.EXPIRE) {
          app.globalData.token = ''
          showToast(`登录过期, 请重新刷新页面`)
          reject(res.data)
        } else {
          // showToast(`请求错误${url}, CODE: ${code}`)
          console.log("success  请求错误:" + code);
          reject(res.data)
        }
        console.log("success  statusCode:1111111111");
      },
      fail: (err) => {
        console.log("Error  " + err);
        if (isShowLoding) {
          wx.hideLoading(); // 隐藏加载动画
        }
        // showToast(err.errMsg)
        reject(err)
      }
    })
  })
}
function objToQueryString(obj) {
  return Object.keys(obj)
      .map(key => {
          // 对键和值进行 URL 编码
          return `${encodeURIComponent(key)}=${encodeURIComponent(obj[key])}`;
      })
      .join('&'); // 将所有键值对用 '&' 连接起来
}
// 封装toast函数
function showToast(title, icon = 'none', duration = 2500, mask = false) {
  wx.showToast({
    title: title || '',
    icon,
    duration,
    mask
  });
}
 
function get(options) {
  return request({
    method: 'GET',
    ...options
  })
}
 
function post(options) {
  // url, data = {}, ignoreToken, form
  return request({
    method: 'POST',
    ...options
  })
}
 
module.exports = {
  request,
  get,
  post
}