1、封装为一个HTTP类
http.js
/**
* 封装wx.request
*/
// 对象的解构赋值传参
class HTTP {
request({
url,
data = {},
header = {},
method = 'GET',
isShowLoading = true,
title = '加载中',
dealWithHasNoUserId = false
}) {
return new Promise((resolve, reject) => {
this._request({resolve, reject, url, data, header, method, isShowLoading, title, dealWithHasNoUserId})
})
}
/**
*
* 微信网络请求接口
*/
_request({resolve, reject, url, data, header, method, isShowLoading, title, dealWithHasNoUserId}) {
//是否需要加载图标
if (isShowLoading) {
wx.showLoading({
title: title,
mask: true // 显示透明蒙层,防止触摸穿透
})
}
wx.request({
url: url,
method: method,
data: data,
header: header,
success: (res) => {
// 只要成功接收到服务器返回,无论 statusCode 是多少,都会进入 success 回调。所以要根据业务逻辑对返回值进行判断
const code = res.statusCode.toString()
// 对于前端来说2开头的都是成功的,如果是201则捕获错误
if (code.startsWith('2')) {
if (code.endsWith('0')) { // 200,绝对的成功
resolve(res.data)
} else {
// 如果这里还有后台返回其他状态的错误,那么就在这里进行判断,进行详细报错处理
reject(res)
let errMes = res.data.msg || "出错了~"
this._show_error(errMes)
}
} else if (code.startsWith('4')) {
reject(res)
this._show_error(`客户端错误[${code}]`)
} else if (code.startsWith('5')){
reject(res)
this._show_error(`服务端错误[${code}]`)
} else {
reject(res)
const error_code = res.data.msg || "出错了~"
this._show_error(error_code)
}
if (isShowLoading) {
wx.hideLoading()
}
},
fail: (err) => {
reject(err)
let errMes = res.data.msg || "出错了~"
this._show_error(errMes)
if (isShowLoading) {
wx.hideLoading()
}
}
})
}
/**
*
* 报错提示处理
*/
_show_error(err) {
wx.showToast({
title: err,
icon: 'none',
duration: 2000
})
}
}
export { // es6语法导出,需要使用import来引入
HTTP
}
2、调用类中的request()请求方法
方法一:非继承式调用类中的方法
import { // 引入模块
HTTP
} from 'http.js'
// 类的实例化
const http = new HTTP()
// 调用类中的方法,这里使用实例对象http来调用
http.request({
url: xxxxxx,
header: {
// ...
},
data: {
//....
},
method: 'POST'
}).then((res) => {
console.log(res)
})
方法二:继承式调用类中的方法
import { // 引入模块
HTTP
} from 'http.js'
class USER extends HTTP {
userFunction () {
// 调用类中的方法,这里直接使用this来调用
this.request({
url: xxxxxx,
header: {
// ...
},
data: {
//....
},
method: 'POST'
}).then((res) => {
console.log(res)
})
}
}
其他功能添加配置参考:(请求锁,请求超时时间设置)
https://www.jianshu.com/p/bf8a8ca68f69
更完整的封装参考:
https://blog.csdn.net/weixin_37880401/article/details/89141182