/**
* 封装wx.request
*/
import { config } from './config';
const apis = require('./api');
//接口白名单
let whiteList = [
apis.api.login
];
class HTTP {
request({
url,
data = {},
header = config.headers,
method = 'POST',
isShowLoading = true,
title = '加载中',
}) {
return new Promise((resolve, reject) => {
if (whiteList.includes(url)) {
//白名单内直接触发请求
this._request(resolve, reject, url, data, header, method, isShowLoading, title)
} else {
/**
* 白名单外判断是否存在用户
*/
let hasUser = wx.getStorageSync('hasUser');
if (hasUser) {
this._request(resolve, reject, url, data, header, method, isShowLoading, title)
} else {
console.error("Error! 请先绑定用户")
}
}
});
}
/**
*
* 微信网络接口
*/
_request(resolve, reject, url, data = {}, header = {}, method, isShowLoading, title) {
//是否需要加载图标
if (isShowLoading) {
wx.showLoading({
title: title,
})
}
wx.request({
url: config.baseUrl + url,
method: method,
data: data,
header: header,
success: (res) => {
console.log(url, '----->', data, '---->', res)
const code = res.statusCode.toString()
if (isShowLoading) {
wx.hideLoading()
}
// 200,绝对的成功,如果是201则捕获错误
if (code.startsWith('2')) {
if (code.endsWith('0')) { // 200,绝对的成功
resolve(res.data)
} else {
reject(res)
}
} else if (code.startsWith('4') || code.startsWith('5')) {
if (isShowLoading) {
wx.hideLoading()
}
this._show_error(`服务端错误[${code}]`)
} else {
reject(res)
const error_code = res.data.msg
this._show_error(error_code)
}
},
fail: (err) => {
reject(err)
this._show_error('网络连接失败')
if (isShowLoading) {
wx.hideLoading()
}
}
})
}
/**
*
* 报错处理
*/
_show_error(err) {
wx.showToast({
title: err,
icon: 'none',
duration: 4000
})
}
}
export {
HTTP
}