这几天开发微信小程序,发现了点请求方面的问题,每个请求都要写相同类型的异常,就简单封装了一下wx.request
首先在utils里面创建一个api.js 文件
const host = "http://www.api.com";
function request(url, data, method) {
return new Promise((resolve, reject) => {
wx.showLoading({
title: '加载中',
duration: 3000
})
wx.request({
url: host + url,
data: data || {},
header: {
'Content-Type': 'application/json;charset=UTF-8',
‘token’:wx.getStorageSync('token')
},
method: method || 'GET',
success: (res) => {
wx.hideLoading()
let statusCode = res.statusCode
if (statusCode === 200 ) {
resolve(res.data)
} else {
wx.showToast({
title: '网络异常,请检查网络状态',
icon: 'none',
duration: 3000
})
reject(res)
}
},
fail: (r