代码如下:
//app.js
App({
globalData: {
urlPath: "http://www.baidu.com//", //此处貌似必须填写搜索引擎的网址,我尝试了百度,360,搜狗都可以,腾讯搜搜不行
userInfo: null,
openid: null,
},
onLaunch: function () {
// 展示本地存储能力
var logs = wx.getStorageSync('logs') || []
logs.unshift(Date.now())
wx.setStorageSync('logs', logs)
// 登录
wx.login({
//获取code
success: res => {
var code = res.code; //返回code
var appId = '你的小程序id';
var secret = '你的小程序密钥';
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: res => {
var openid = res.data.openid //返回openid
console.log('openid为' + openid);
this.globalData.openid = openid
}
})
}
})
// 获取用户信息
wx.getSetting({
success: res => {
if (res.authSetting['scope.userInfo']) {
// 已经授权,可以直接调用 getUserInfo 获取头像昵称,不会弹框
wx.getUserInfo({
success: res => {
// 可以将 res 发送给后台解码出 unionId
this.globalData.userInfo = res.userInfo
console.log(res);
// 由于 getUserInfo 是网络请求,可能会在 Page.onLoad 之后才返回
// 所以此处加入 callback 以防止这种情况
if (this.userInfoReadyCallback) {
this.userInfoReadyCallback(res)
}
}
})
}
}
})
},
})
反复比对代码好多次都没啥问题,可是下面的this.globalData.userInfo就可以执行上面的this.globalData.openid就报错说golbalData未定义,原因如下:
success方法那里必须用success: res => {}的格式,我之前上面的用的是success:function(e){}格式就不行