index.wxml中的授权登录代码:
<button class='btn-check' bindtap="login" wx:if="{{agree != ''}}" >
<label>微信授权登录</label>
</button>
index.js中的data里放入请求的参数说明
data: {
agree:'agree',
code:'',
userInfo: {},
rawData:{},
signature:'',
encryptedData:'',
iv:'',
},
bindtap记为login(),在js中将wx.login()和wx.request()均放在在login()中
切记wx.request()不能放在login()外,否则的连接不到后端接口数据的
login(){
wx.login({
success:(res)=>{
this.setData({
code:res.code
})
}
})
wx.getUserProfile({
desc: '用于登录账号,完善身份信息',
success: (res) => {
this.setData({
userInfo:res.userInfo,
rawData:res.rawData,
signature:res.signature,
encryptedData:res.encryptedData,
iv:res.iv,
})
wx.request({//请求接口
url: 'xxxxxx', //接口地址
data:{
"authType":1,
"code":that.data.code,
"rawData":that.data.rawData,
"signature":that.data.signature,
"encryptedData":that.data.encryptedData,
"iv":that.data.iv,
},
method:"POST",
header: {
'content-Type': 'application/json',
},
dataType: 'json',
success: function (res) {
// 一般在这一打印下看看是否拿到数据
console.log(res.data.data)
},
// 请求失败时的一些处理
fail: function () {
// console.log('userI现场支持nfo');
wx.showToast({
icon: "none",
mask: true,
title: "接口调用失败,请稍后再试。",
});
}
})
}
})
最后点击登录,在后端数据库和前端控制台均可得到数据:(如下图所示)
则请求数据成功。