7月21日工作进程
由于后端的登录有验证token的步骤,所以存在发送请求之前检验token的合法性的问题。经过讨论,有两种可行的解决方案,一种是每次小程序加载的时候更新一次token,保证每次使用的token都是最新的,第二种是在小程序端实现过期token的拦截。经过仔细思考与权衡,最终选择了第一种方案,因为第二种方案不仅实现困难,可控参考的资源少,而且没有必要。所以在app.js onLaunch()中调用登录的接口。同时因为需要在进入小程序是确定未读消息的数目决定是否展示未读消息的小红点,所以需要吧登录的接口改为同步模式。
app.js
onLaunch() {
util._login().then((res) => {
console.log("在app.js onLaunch 调用 login完成");
util.checkUnreadNum();
}).catch((err) => {
console.log(err)
})
}
util.js
function checkUnreadNum() {
return new Promise((resolve, reject) => {
wx.request({
url: 'http://grandland.gl-data.com:14332/message/getnumber',
method: 'GET',
header: {
'content-type': 'application/json',
'token': wx.getStorageSync("skey"),
},
timeout: 1000,
success(res) {
getApp().globalData.unreadNum = res.data
if (getApp().globalData.unreadNum == 0) {
wx.hideTabBarRedDot({
index: 1,
})
} else {
wx.showTabBarRedDot({
index: 1,
})
}
resolve(res)
},
fail(err) {
console.log("get Message Number fail", err)
reject(err)
},
complete() {}
})
})
}
function _login() {
return new Promise((resolve, reject) => {
wx.login({
success: function (res) {
var code = res.code;
if (code) {
console.log('获取用户登录凭证:' + code);
wx.request({
url: 'http://grandland.gl-data.com:14332/Login',
data: {
codeID: code
},
header: {
"Content-Type": "application/x-www-form-urlencoded"
},
method: "POST",
success: function (res) {
if (res.statusCode == 200) {
wx.setStorageSync('skey', res.data.data);
resolve(res)
} else {
console.log('服务器异常');
}
},
fail: function (error) {
console.log(error);
}
})
} else {
console.log('获取用户登录态失败:' + res.errMsg)
}
},
fail: function (err) {
reject(err)
}
});
})
}