3,143
社区成员
发帖
与我相关
我的任务
分享
// 判断token 是否过期
var tokenDate = wx.getStorageSync('tokenDate') || 'null';
console.log(tokenDate)
if (tokenDate == 'null') { // 如果为空的情况下 则去请求token 并缓存
wx.request({
url: 'http://api.hmxigou.com/api/5c22de286985d',
method: 'GET',
header: {
'Content-Type': 'application/json',
'version': 'v3.0'
},
data: {},
success: (res) => {
//定义当前时间戳
var timestamp = Date.parse(new Date());
//定义过期时间
var mytime = timestamp + 7200000; //2个小时
//存储token
//.... 请求成功回调
wx.setStorageSync('tokenDate', mytime); // token结束时间
wx.setStorageSync('access_token', res.data.data.access_token)
console.log(res)
console.log('过期时间为空时定义缓存')
console.log(wx.getStorageSync('access_token'));
},
fail: (res) => {
wx.showToast({
title: '网络异常',
duration: 2000
})
}
})
} else { // 有token 的情况下 判断token 是否有效
var nowDate = Date.parse(new Date());
var tokenEndTime = wx.getStorageSync('tokenDate');
//var endTime = new Date(tokenEndTime).getTime();
if (nowDate >= tokenEndTime) { // 如果过期则 更新 token & token 时间
//nowDate.setMonth(nowDate.getMonth() + 3);
wx.request({
url: 'http://api.hmxigou.com/api/5c22de286985d',
method: 'GET',
header: {
'Content-Type': 'application/json',
'version': 'v3.0'
},
data: {},
success: (res) => {
//定义当前时间戳
var timestamp = Date.parse(new Date());
//定义过期时间
var mytime = timestamp + 7200000; //2个小时
//存储token
//.... 请求成功回调
wx.setStorageSync('tokenDate', mytime); // token结束时间
wx.setStorageSync('access_token', res.data.data.access_token)
console.log(res)
console.log('缓存到期了')
//console.log(wx.getStorageSync('access_token'));
},
fail: (res) => {
wx.showToast({
title: '网络异常',
duration: 2000
})
}
})
}
}
}