封装 uniapp request请求
/**
* 请求数据处理
* @param string url 请求地址
* @param {*} postData 请求参数
* @param string method 请求方式
* GET or POST
* @param string contentType 数据格式
* 'application/x-www-form-urlencoded'
* 'application/json'
* @param bool isDelay 是否延迟显示loading
* @param bool hideLoading 是否隐藏loading
* true: 隐藏
* false:显示
*/
request: function(url, postData = {}, method = "POST", contentType = "application/x-www-form-urlencoded", isDelay, hideLoading) {
//接口请求
let loadding = false;
utils.delayed && uni.hideLoading();
clearTimeout(utils.delayed);
utils.delayed = null;
if (!hideLoading) {
utils.delayed = setTimeout(() => {
uni.showLoading({
mask: true,
title: '请稍候...',
success(res) {
loadding = true
}
})
}, isDelay ? 1000 : 0)
}
return new Promise((resolve, reject) => {
uni.request({
url: utils.interfaceUrl() + url,
data: postData,
header: {
'content-type': contentType,
'token': utils.getToken()
},
method: method, //'GET','POST'
dataType: 'json',
success: (res) => {
if (loadding && !hideLoading) {
uni.hideLoading()
}
if (res.statusCode === 200) {
if (res.data.errno === 401) {
//返回码401说明token过期或者用户未登录
uni.removeStorage({
key: 'token',
success() {
//个人中心页不跳转
if (uni.getStorageSync("navUrl") != "/pages/ucenter/index/index") {
utils.modal('温馨提示', '您还没有登录,是否去登录', true, (confirm) => {
if (confirm) {
uni.redirectTo({
url: '/pages/auth/btnAuth/btnAuth',
})
} else {
uni.navigateBack({
delta: 1,
fail: (res) => {
uni.switchTab({
url: '/pages/index/index',
})
}
})
}
})
}
}
})
} else if (res.data.errno === 500) {
utils.toast(res.data.msg)
} else if (res.data.errno === 404) {
utils.toast(res.data.msg)
} else {
resolve(res.data);
}
} else {
reject(res.data.msg);
}
},
fail: (res) => {
utils.toast("网络不给力,请稍后再试~")
reject(res)
},
complete: function(res) {
clearTimeout(utils.delayed)
utils.delayed = null;
if (res.statusCode === 200) {
if (res.data.errno === 0 || res.data.errno === 401) {
uni.hideLoading()
} else {
utils.toast(res.data.msg)
}
} else {
utils.toast('服务器开小差了~')
}
}
})
})
},