Home > Mobile >  Cache in the app access token is a null value for the first time, refresh again to get to the, what
Cache in the app access token is a null value for the first time, refresh again to get to the, what

Time:09-28

I used the front-end cache to determine whether a token exists, if there is a time to judge whether the past, but have a problem, onLaunch is asynchronous, total after onl oad execution, for the first time, this leads to access token is empty, only after the refresh once access to the value, this how the whole App. Js code is as follows:
 
//determine whether token expired
Var tokenDate=wx. GetStorageSync (' tokenDate ') | | 'null';
The console. The log (tokenDate)
If (tokenDate=='null') {//if the empty cases to request token and cache
Wx. Request ({
Url: 'http://api.hmxigou.com/api/5c22de286985d',
Method: 'GET',
Header: {
'the content-type:' application/json,
'version' : 'v3.0'
},
Data: {},
Success: (res)=& gt; {
//define the current timestamp
Var timestamp=Date. Parse (new Date ());
//define the expiration time
Var mytime=timestamp + 7200000;//2 hours
//store token
//... Request success callback
Wx. SetStorageSync (' tokenDate, mytime);//token end time
Wx. SetStorageSync (" access_token ", res. Data. The data. The access_token)
The console. The log (res)
The console. The log (' expiration time is empty defined when the cache)
The console. The log (wx. GetStorageSync (" access_token "));
},
Fail: (res)=& gt; {
Wx. ShowToast ({
Title: 'network anomalies,
Duration: 2000
})
}
})
} else {//a token of cases to determine whether a token effective
Var nowDate=Date. Parse (new Date ());
Var tokenEndTime=wx. GetStorageSync (' tokenDate ');
//var endTime=new Date (tokenEndTime). GetTime ();

If (nowDate & gt;=tokenEndTime) {//if the overdue is updated token & amp; Token time
//nowDate setMonth (nowDate getMonth () + 3);
Wx. Request ({
Url: 'http://api.hmxigou.com/api/5c22de286985d',
Method: 'GET',
Header: {
'the content-type:' application/json,
'version' : 'v3.0'
},
Data: {},
Success: (res)=& gt; {
//define the current timestamp
Var timestamp=Date. Parse (new Date ());
//define the expiration time
Var mytime=timestamp + 7200000;//2 hours
//store token
//... Request success callback
Wx. SetStorageSync (' tokenDate, mytime);//token end time
Wx. SetStorageSync (" access_token ", res. Data. The data. The access_token)
The console. The log (res)
The console. The log (' cache expire)
//the console. The log (wx. GetStorageSync (" access_token "));
},
Fail: (res)=& gt; {
Wx. ShowToast ({
Title: 'network anomalies,
Duration: 2000
})
}
})
}
}
}

CodePudding user response:

Haven't over the years? My top

CodePudding user response:

I encountered this problem right now? How to solve
  • Related