1. button 标签和 open-type=“getUserInfo” 获取用户信息失败
天哪噜,必须好好记录一番由于没有看官方文档更新 api 而导致的 “BUG” !!!
一觉醒来,发现准备收尾的小程序无法获取到用户信息了???怎么回事,于是一顿焦虑 + 骚操作,各种找 BUG
这种用户信息,获取了个寂寞啊???
贴出原代码:
wxml:
<button bindgetuserinfo="handleGetuserInfo" open-type="getUserInfo">
登录
</button>
js:
handleGetuserInfo(e) {
var that = this
console.log("handlegetuserinfo:", e)
// 2 用于前端显示
const {
userInfo
} = e.detail;
wx.setStorageSync('userInfo', userInfo)
//访问数据库
that.login()
},
2. 改用 button 标签 和 wx.getUserProfile() 成功获取用户信息
查看官方文档更新日志后
参照文档修改代码如下:
wxml:
<button bindtap="getUserProfile">
登录
</button>
js:
// 新版获取用户信息
getUserProfile(e) {
var that = this
wx.getUserProfile({
desc: '用于完善用户资料',
success: (res) => {
this.setData({
// 此处左边的 userInfo 是js data 中定义的全局变量
// res.userInfo 是调用接口返回的数据
userInfo: res.userInfo
})
// 将得到的用户信息 userInfo 保存到缓存中
wx.setStorageSync('userInfo', this.data.userInfo)
// 输出检查看看
console.log("getuserProfile:", res.userInfo)
//调用自定义的 login() 方法访问数据库,将用户信息保存到数据库
that.login()
}
})
},
// 登录
login() {
// 获取缓存中的用户信息
const userInfo = wx.getStorageSync('userInfo');
console.log("userInfo:", userInfo)
// 如果缓存中有用户信息
if (userInfo) {
// 获取微信小程序登陆成功后的code
wx.login({
timeout: 500,
success: (result) => {
// 1 成功取得 code
const {
code
} = result;
console.log("code:", code)
// 2 发送请求到后台 换取 openid
// 这里 request() 是自己封装的 es6 的 promise 的方式,读者可以直接使用 wx.request()
request({
url: app.globalData.url + '/index.php/code',
data: {
code: code
},
method: 'get',
})
.then(res => {
this.setData({
openid: res.data.openid,
})
//将 openid 保存到缓存中
wx.setStorage({
key: 'openid',
data: res.data.openid
})
// 将用户信息保存到数据库表中
request({
url: app.globalData.url + '/index.php/login',
data: {
u_nickName: userInfo.nickName,
u_sex: userInfo.gender,
u_imgUrl: userInfo.avatarUrl,
u_openid: res.data.openid
},
method: "get"
})
.then(res => {
console.log(res)
if (res.data.msg == "success") {
wx.showModal({
content: '登录成功
showCancel: false,
})
// 登录成功后刷新当前页面,以显示用户信息和用户数据
this.onShow();
}
})
})
},
})
}
},
成功获取用户信息:
要是大家发现一直没有问题的代码突然出现了意料之外的 BUG ,一波排除后,可以看看官方文档更新日志,说不定和我一样,发现是 api 的锅呢? Gook Luck !
By the way~~ 不知道是不是有人和我一样不知道可以这样查看日志:
若有不正确之处,请指正~ 谢谢