I'm a Linux sysadmin with very little coding experience. I was asked to develop a demo RCS chatbot in nodejs that would echo back any message it gets. I'm surprised I even got as far as I did, and I only have one last thing to do. I'm really enjoying this project and I was hoping I could ask for some help for the last piece. I'm trying to create a variable OD
and put the value of access_token
I have this part of my code:
request5(options5, function (error, responseOD) {
if (error) throw new Error(error);
console.log(responseOD.body); // <--------------------------- Third line
var OD = responseOD.body.access_token;
console.log(OD); // <------------------------------- Fifth line
var ODtoken = "Bearer ".concat(OD);
});
The third line (I've written "third line" in the code snippet) returns this:
{
"token_type": "Bearer",
"access_token": "cbYAmA9iElLteoAQrj9GsDT2VrnD",
"expires_in": "7776000"
}
but for some reason, the fifth line (console.log(OD);
, I've written "fifth line" in the code snippet) returns:
undefined
Does anyone know why the OD
variable won't receive the access_token
from the JSON response?
Huge thanks ahead!
You just want to parse that string body into a Javascript object using JSON.parse(string)
function. In the end your code should look like this:
request5(options5, function (error, responseOD) {
if (error) throw new Error(error);
var bodyAsObject = JSON.parse(responseOD.body);
var OD = bodyAsObject.access_token;
var ODtoken = "Bearer ".concat(OD);
});