I am trying to write a function that will just return part of the JSON response to the calling function. This is what I have
function returnToken()
{
var https = require('follow-redirects').https;
var fs = require('fs');
var qs = require('querystring');
var options = {
'method': 'POST',
'hostname': hostname,
'path': path,
'headers': {
'Accept': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded',
'Cookie': 'AWSALBTG=VQeZ4MBoHfHiCgR7g4DBcvuSGVQgDKDPo95l9tiNlSv9WNmDW1Z6PqXjKOTP3LKeqkHw5//8vIH304VbApkBRePHFM8JVgOtmqpRpv9iVN+cYS73RiNl+kxWSnntRZQ4+oXnFkG5NVlZty+ohK8qyX1UhQDT5+UGhV9Kn9heLkbG; AWSALBTGCORS=VQeZ4MBoHfHiCgR7g4DBcvuSGVQgDKDPo95l9tiNlSv9WNmDW1Z6PqXjKOTP3LKeqkHw5//8vIH304VbApkBRePHFM8JVgOtmqpRpv9iVN+cYS73RiNl+kxWSnntRZQ4+oXnFkG5NVlZty+ohK8qyX1UhQDT5+UGhV9Kn9heLkbG'
},
'maxRedirects': 20
};
var req = https.request(options, function (res) {
var chunks = [];
res.on("data", function (chunk) {
chunks.push(chunk);
});
res.on("end", function (chunk) {
var body = Buffer.concat(chunks);
console.log(JSON.parse(body).access_token);
return JSON.parse(body).access_token;
});
res.on("error", function (error) {
console.error(error);
});
});
var postData = qs.stringify({
'client_id': clientID,
'client_secret': clientSecret,
'scopes': scope,
'grant_type': 'client_credentials'
});
req.write(postData);
req.end();
}
const t=returnToken();
console.log('t='+t);
When I run this code, the function runs and then outputs the access_token to the console just fine. However, by putting return JSON.parse(body).access_token; in the code where I did, I thought it would return the access function to the calling code. It doesn't. t is undefined. I'm kind of at a loss as to how to return that value.