我用了前端快取判斷token是否存在,如果存在判斷時間是否過去來實作,但是遇到問題了,onLaunch是異步的,總在onLoad之后執行,這就導致第一次獲取的token是空值,只有在重繪一次后才會獲取到值,這個該怎么整,App.js里代碼如下:
// 判斷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
})
}
})
}
}
}
uj5u.com熱心網友回復:
都還沒過完年嗎?我自己頂一下uj5u.com熱心網友回復:
我現在就遇到這種問題?怎么解決轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/91378.html
標籤:微信開發
