//请求包装
var myrequest = function (requestobj){
if ((!requestobj.header ||requestobj.header.auth==null)){
console.log("没有请求权限代码,API有方法可以判断两个用户是不是好友么? 微信小程序开发教程。默认无权限要求请求");
}else{
if ((requestobj.header.auth == 1 || requestobj.header.auth == 2) && !token) {//需要登录且未登录
console.log("需要登录且未登录");
login(myrequest, requestobj);//调用登录,登录完成后回调请求
return;
} else if (requestobj.header.auth == 2) {//需绑定手机号且未绑定手机号
console.log("需认证且未认证");
bind();//调用绑定手机号弹出框
return;
} else {
console.log("通过验证,准备向服务器发送请求");
}
}
wx.request({
url: requestobj.url,
data: requestobj.data,
header: Object.assign({
'content-type': 'application/json',
'token': token
}, requestobj.header),
method: requestobj.method != null ? requestobj.method:"GET",
success: function (res) {
console.log(res.data);
if (res.statusCode == 200||res.statusCode==304) {
if (res.data.errcode == 0) {
typeof requestobj.success == "function" && requestobj.success(res)
} else {
wx.showToast({
title: res.data.errmsg,
image: '/images/icon/error.png',
duration: 3000
})
}
}else{
wx.showToast({
title: "服务器响应失败",
image: '/images/icon/error.png',
duration: 3000
})
}
},
fail: function (res) {
wx.showToast({
title: "请求失败",
image: '/images/icon/error.png',
duration: 3000
})
typeof requestobj.fail == "function" && requestobj.fail(res)
},
complete: function () {
typeof requestobj.complete == "function" && requestobj.complete()
}
})
}
//登录
var login = function (cb, requestobj){
if (token){
console.log("已登录");
}else{
console.log("调用登录");
wx.login({
success:function(res){
if (res.code) {
console.log(res.code);
myrequest({
url: requestUrl.loginUrl,
data: { code: res.code},
method:"POST",
success: function (res){
token = res.data.data.openid;
console.log(token);
typeof cb == "function" && cb(requestobj)
}
})
} else {
console.log('获取用户登录态失败!' + res.errMsg)
}
}
})
}
}
//一般请求
myrequest({
url: requestUrl.indexRequestUrl,
data: {
showAgent: 1
},
header:{//0、直接请求 1、需登录请求 2.需登录且绑定手机后请求
auth:1
},
success:function(res){
console.log("私success");
that.setData({
Carousel: res.data.data.Carousel,
Menu: res.data.data.Menu
})
}
});
本文网址:http://www.91bianli.com/weixinxiaochengxu/52047.html