I have generated this code snippet from insomnia that is making a request to an API for an access token. This access token will then be used in another request to retrieve some data via the same API (in the same manner). I want to be able to return the accessToken variable so that when I call the getAccessToken() function it returns the token as a string. My issue is, when I use return accessToken and call the function it comes back as undefined, but when I console log the accessToken (within res.on("end"..)) it prints the token as a string. I have a feeling this is a scope issue but I'm not quite sure how to fix it.
In short, my desired result is to call getAccessToken() and have the function return the access token as a string.
Any help is greatly appreciated!
function getAccessToken() {
const http = require("https");
var accessToken;
const options = {
"method": "POST",
"hostname": "omitted for security reasons",
"port": null,
"path": "/auth",
"headers": {
"Content-Length": "0",
"Authorization": "Bearer **omitted for security reasons**"
}
};
req = http.request(options, function (res) {
const chunks = [];
res.on("data", function (chunk) {
chunks.push(chunk);
});
res.on("end", function () {
const body = Buffer.concat(chunks);
accessToken = body.toString();
return accessToken;
//console.log(accessToken);
});
});
req.end();
}
console.log(getAccessToken());