const baseUrl = ''
export function request(url, method, data, header) {
return new Promise(function (resolve, reject) {
wx.request({
url: baseUrl + url,
method: method,
data: method === 'POST' ? JSON.stringify(data) : data,
header: {
'content-type': 'application/json',
'X-Auth-Token': getApp().globalData.token,
...header
},
success(res) {
if (res.statusCode == 200) {
resolve(res.data)
}else {
reject()
wx.showToast({
title: '服务器异常',
icon: 'none',
duration: 2000
})
}
},
fail(err) {
reject()
wx.showToast({
title: '服务器异常',
icon: 'none',
duration: 2000
})
}
})
})
}
外部模块引用后使用async+await即可
本文介绍了一种在微信小程序中进行网络请求的封装方法,通过使用Promise实现异步请求,并利用async/await简化调用过程。该封装考虑了错误处理及状态码验证。
1078

被折叠的 条评论
为什么被折叠?



