最近我在使用SAP云平臺(tái)的機(jī)器學(xué)習(xí)API做和SAP系統(tǒng)的集成,因?yàn)镾AP Cloud Platform Leonardo上的機(jī)器學(xué)期API,每次消費(fèi)時(shí)需要傳一個(gè)Access Token,故在每次實(shí)際調(diào)用API前,我需要先發(fā)一個(gè)請(qǐng)求去獲取Access Token. 該請(qǐng)求的響應(yīng),除了返回實(shí)際的token外,還有一個(gè)過期時(shí)間,expires_in字段:
成都創(chuàng)新互聯(lián)主要從事成都做網(wǎng)站、網(wǎng)站制作、成都外貿(mào)網(wǎng)站建設(shè)、網(wǎng)頁設(shè)計(jì)、企業(yè)做網(wǎng)站、公司建網(wǎng)站等業(yè)務(wù)。立足成都服務(wù)港南,10余年網(wǎng)站建設(shè)經(jīng)驗(yàn),價(jià)格優(yōu)惠、服務(wù)專業(yè),歡迎來電咨詢建站服務(wù):028-86922220
根據(jù)OAuth 2.0標(biāo)準(zhǔn)定義,expires_in字段代表服務(wù)器頒發(fā)的該token,距離過期時(shí)間還剩的秒數(shù)。
我的代碼如下:
const request = require('request-promise-native'); var config = require('../config.js'); var TOKEN = undefined; var EXPIRES_IN = undefined; var TOKEN_FETCHED_SINCE = undefined; function isCurrentDateExpired(){ var current = new Date(); var diffInMilliSeconds = current - TOKEN_FETCHED_SINCE; var diffInSecond = Math.ceil(diffInMilliSeconds/1000); var expired = diffInSecond >= EXPIRES_IN ? true:false; // for debug; // expired = true; return expired; } async function getAccessToken(){ if( TOKEN === undefined || isCurrentDateExpired()){ var raw = new Buffer(config.username + ":" + config.password); const accessToken = await request({ method: 'GET', headers: { 'Authorization': 'Basic ' + raw.toString('base64') }, url: config.ACCESS_TOKEN, json: false }); var oToken = JSON.parse(accessToken); EXPIRES_IN = oToken.expires_in; TOKEN = oToken.access_token; TOKEN_FETCHED_SINCE = new Date(); return oToken.access_token; } else{ return TOKEN; } } var request1 = getAccessToken(); var freshNewToken, secondTimeToken; request1.then(function(o){ // console.log("token1: " + o); freshNewToken = o; }); function test2(){ var b = getAccessToken(); b.then(function(o){ // console.log("token2: " + o); secondTimeToken = o; console.log("they should be equal: " + (freshNewToken == secondTimeToken)); }); } setTimeout( test2, 6000);
要獲取更多Jerry的原創(chuàng)文章,請(qǐng)關(guān)注公眾號(hào)"汪子熙":