到处都要用到的access_token的获取和缓存!
官方说可以每次都重新获取,我建议还是缓存下来比较好。我用了Redis, 你也可以用其他你喜欢的方式。
把获取的代码封装一个函数,getAccessToken返回Promise 对象,每次调用成功后在继续下一步操作!
const config = require('./config')
const https = require('https')
var request = require('request');
const moment = require("moment")
const qs = require('querystring')
var fs = require("fs")
const redis = require('then-redis')
const db = redis.createClient('tcp://localhost:6379')
function getAccessToken(){
return new Promise((resolve, reject)=>{
db.hgetall('AccessToken').then((res)=>{
if(res){
if(res.enddate <= moment().format("YYYY-MM-DD")){
var data = {
'grant_type': 'client_credentials',
'client_id': config.APIKey,
'client_secret': config.SecretKey
};//这是需要提交的数据
var content = querystring.stringify(data);
var options = {
hostname: 'aip.baidubce.com',
path: '/oauth/2.0/token?' + content,
method: 'GET'
};
var req = https.request(options, function(res){
res.setEncoding('utf8');
res.on('data', function (chunk) {
chunk = JSON.parse(chunk)
var obj = {
value: chunk.access_token,
enddate: moment().add(29, 'days').format("YYYY-MM-DD")
}
db.hmset("AccessToken", obj)
resolve(obj);
});
})
req.on('error', function (e) {
reject('problem with request: ' + e.message);
});
req.end()
}else{
resolve(res)
}
}else{
var data = {
'grant_type': 'client_credentials',
'client_id': config.APIKey,
'client_secret': config.SecretKey
};//这是需要提交的数据
var content = qs.stringify(data);
var options = {
hostname: 'aip.baidubce.com',
path: '/oauth/2.0/token?' + content,
method: 'GET'
};
var req = https.request(options, function(res){
res.setEncoding('utf8');
res.on('data', function (chunk) {
chunk = JSON.parse(chunk)
var obj = {
value: chunk.access_token,
enddate: moment().add(29, 'days').format("YYYY-MM-DD")
}
db.hmset("AccessToken", obj)
resolve(obj);
});
})
req.on('error', function (e) {
reject('problem with request: ' + e.message);
});
req.end()
}
}).catch((err)=>{
reject(err)
})
})
}