我一直在研究和测试如何在节点js中进行API调用。我目前正在尝试使用从模块中的API调用返回的JSON对象的一部分来返回令牌。
var request = require("request");
var timestamp = require("unix-timestamp");
var jwt = require("jsonwebtoken");
var EventEmitter = require("events").EventEmitter;
timestamp.round = true;
//create current unix timestamp
var current = timestamp.now();
//create unix experation time
var experation = timestamp.add(current, "+5m");
//create header
var header = {"header"}
//create payload
var payload = {
"iss": process.env.CKEY,
"aud": "https://iformbuilder.com/exzact/api/oauth/token",
"exp": experation,
"iat": current
};
var signature = process.env.SKEY;
//Create assertion
var assert = jwt.sign(payload, signature);
var grant = 'urn:ietf:params:oauth:grant-type:jwt-bearer';
//set the options
var options = { method: 'POST',
url: 'https://iformbuilder.com/exzact/api/oauth/token',
qs: {
grant_type: grant,
assertion: assert
},
headers: {
'content-type': 'application/x-www-form-urlencoded',
'cache-control': 'no-cache'
}
};
var data = {};
var tkn = new EventEmitter();
module.exports = {
token: function() {
request(options, function (error, response, body) {
if (error) throw new Error(error);
console.log(body);
tkn.body = body;
tkn.emit('update');
});
tkn.on('update', function(){
data = JSON.parse(tkn.body);
return data.access_token;
});
}
}
问题是我只能在tkn.on范围内使用返回的项目。我可以在其中嵌套另一个API调用以使用令牌。但是,我想使用它而不必再次使用相同的代码。我可以使用的唯一解决方案是写入文件。我想知道我是否正在按照正确的方式进行操作。我似乎在网上找不到任何好的资源可以帮助我解决这个问题,也许我问的是错误的问题。
最佳答案
您必须使用回调(或Promise)来获取值。以下是带有回调的示例,我将让您研究promise。我想说的是,首先通过回调了解它,然后继续进行promise。
someOtherModule.js
var tokenGetter = require('./tokenGetter');
function doSomethingWithToken(accessToken){
//Do what you want with the token here
}
tokenGetter.token(doSomethingWithToken);
tokenGetter.js
module.exports = {
token: function(callback) {
request(options, function (error, response, body) {
if (error) throw new Error(error);
console.log(body);
tkn.body = body;
tkn.emit('update');
});
tkn.on('update', function(){
data = JSON.parse(tkn.body);
callback(data.access_token);
});
}
}
您必须执行此操作的原因是因为使用异步操作,您不知道何时会收到响应。代码不再像以前那样线性化。
您必须调整代码以继续其操作,直到收到响应而不是执行操作之后。