1.app.js
// 登录
globalData: {
userInfo: null
},
onLaunch() {
var that=this;
wx.login({
success: res => {
var code = res.code,appId = 'xxxxxxxxxxxxxxxxx',secret = 'xxxxxxxxxxxxxxxxx';
// 发送 res.code 到后台换取 openId, sessionKey, unionId
wx.request({
url: 'https://api.weixin.qq.com/sns/jscode2session?appid=' + appId + '&secret=' + secret + '&js_code=' + code + '&grant_type=authorization_code',
data: {},
header: {
'content-type': 'json'
},
success: function (res) {
// var openid = res.data.openid //返回openid
that.globalData.userInfo=res.data;
//由于这里是网络请求,可能会在 Page.onLoad 之后才返回 所以此处加入 userInfoReadyCallback 以防止这种情况
if (that.userInfoReadyCallback) {
that.userInfoReadyCallback(res.data)
}
}
})
}
})
}
2.index.js
onLoad() {
app.userInfoReadyCallback=res=>{
this.setData({
userInfo:app.globalData.userInfo
});
}
},
网友评论