Files
rlz/coupon/utils/request.js
renjianbo 1d0a0b9b04 feat: add request.js utility, service page, and fix hospital image URLs
- Add request.js for unified API calls with loading/error handling
- Add service page (service type listing)
- Fix hospital list to load from API with proper image URL construction
- Add service types dynamic loading on index page
- Various mini program improvements (order, care, wallet pages)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-06-07 10:13:26 +08:00

90 lines
2.2 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* 通用网络请求工具
* - 自动 loading / hideLoading
* - 自动 fail 错误提示
* - Promise 风格,支持 async/await
* - code != 200 自动 toast 并 reject
*/
const app = getApp()
// 请求计数,支持并发 loading
let requestCount = 0
/**
* @param {object} opts
* @param {string} opts.url - API 路径(不含 baseUrl
* @param {string} opts.method - GET/POST默认 GET
* @param {object} opts.data - 请求参数
* @param {boolean} opts.loading - 是否显示 loading默认 true
* @param {string} opts.loadingText - loading 文案,默认 "加载中..."
* @param {boolean} opts.showError - 失败时是否自动 toast默认 true
* @param {object} opts.header - 自定义 header会合并默认 header
* @returns {Promise<object>} res.data - 响应体 { code, msg, data }
*/
function request(opts) {
const {
url,
method = 'GET',
data = {},
loading = true,
loadingText = '加载中...',
showError = true,
header = {}
} = opts
if (loading) {
if (requestCount === 0) {
wx.showLoading({ title: loadingText, mask: true })
}
requestCount++
}
return new Promise((resolve, reject) => {
wx.request({
url: app.globalData.url + url,
method,
data,
header: {
'content-type': 'application/x-www-form-urlencoded',
'Authorization': 'Bearer ' + app.getCache('token'),
...header
},
success(res) {
if (res.data.code === 200) {
resolve(res.data)
} else {
if (showError) {
wx.showToast({
title: res.data.msg || '请求失败',
icon: 'none',
duration: 2000
})
}
reject(res.data)
}
},
fail(err) {
if (showError) {
wx.showToast({
title: '网络异常,请稍后重试',
icon: 'none',
duration: 2000
})
}
reject(err)
},
complete() {
if (loading) {
requestCount--
if (requestCount <= 0) {
requestCount = 0
wx.hideLoading()
}
}
}
})
})
}
module.exports = { request }