const request = (param) => {
var _self = this,
url = param.url,
method = param.method || "GET",
header = {},
data = param.data || {},
token = "",
hideLoading = param.hideLoading || false;
// 这儿可以添加 token
// 固定参数:仅仅在小程序绑定页面通过code获取token的接口默认传递了参数token = login
if (!data.token) { // 1.其他业务接口传递过来的参数中无token
// token = uni.getStorageSync(this.sessionKey); // 2.参数中无token时在本地缓存中获取
if (!token) { // 3.本地无token需重新登录(退出时清缓存token)
// return
} else {
// header.Authorization = token;
}
}
// 请求方式:GET或POST(POST需配置header: {'content-type' : "application/x-www-form-urlencoded"},)
if (method) {
method = method.toUpperCase(); // 小写改为大写
if (method == "POST") {
header = {
'content-type': "application/x-www-form-urlencoded"
};
header.Authorization = token
} else {
header = {
'Accept': "application/json"
};
header.Authorization = token
}
}
// 用户交互:加载圈
if (!hideLoading) {
uni.showLoading({
title: '加载中...'
});
}
// 拼接完整请求地址
const requestUrl = 'https://api-hmugo-web.itheima.net/api/public/v1/' + url;
return new Promise((resolve,reject)=>{
uni.request({
url: requestUrl,
method: method,
header: header,
data: data,
})
.then(res=>{
// 判断请求是否成功;并做相对于的处理
if(res[1].statusCode == 200){
console.log('成功了')
}
resolve(res[1])
})
// 错误拦截
.catch(err=>{
reject(err)
})
// 不管是否成功都会执行
.finally(()=>{
uni.hideLoading();
})
})
// 一般情况下写到这儿的话也就可以了;下面的代码可以不用了;但是;需要判断请求回来的数据的状态的时候;就可以用下面的这些代码;具体的还是根据工作中的实际情况而定
// 错误判定
// switch (error.status) {
// case 403:
// uni.showToast({
// title: '拒绝访问',
// icon: 'none',
// duration: 4000
// });
// break
// case 500:
// if (data.message == "Token失效,请重新登录") {
// uni.showModal({
// title: '登录已过期',
// content: '很抱歉,登录已过期,请重新登录',
// confirmText: '重新登录',
// success: function(res) {
// if (res.confirm) {
// db.del('userToken')
// //去我的页面登录
// uni.switchTab({
// url: '/pages/views/mine'
// });
// } else if (res.cancel) {
// console.log('用户点击取消');
// }
// }
// })
// // update-end- --- author:scott ------ date:20190225 ---- for:Token失效采用弹框模式,不直接跳转----
// }
// break
// case 404:
// uni.showToast({
// title: '很抱歉,资源未找到!',
// icon: 'none',
// duration: 4000
// });
// break
// case 504:
// uni.showToast({
// title: '网络超时',
// icon: 'none',
// duration: 2000
// });
// break
// case 502:
// uni.showToast({
// title: '服务器异常',
// icon: 'none',
// duration: 2000
// });
// break
// case 401:
// uni.showToast({
// title: '未授权,请重新登录',
// icon: 'none',
// duration: 4000
// });
// if (token == '') {
// setTimeout(() => {
// //去我的页面登录
// uni.switchTab({
// url: '/pages/views/mine'
// });
// }, 1500)
// }
// break
// default:
// uni.showToast({
// title: data.message,
// icon: 'none',
// duration: 4000
// });
// break
// }
}
export default request
uniapp 网络请求封装;前端/小程序
最新推荐文章于 2024-05-30 21:45:00 发布