How to parse Jason data from node.js console.log (response.body);

I have been trying to get this right. My node.js code below returns to console log body of the response. The response has a access_token (JWT bearer). I need to have only the access_token out from the response and reuse the token for the next steps as parameter. Any suggestions appreciated.

var request = require('request');
var options = {
  'method': 'POST',
  'url': 'https://weburl-eu.eu.auth0.com/oauth/token',
  'headers': {
    'Content-Type': 'application/json'
    
  },
  body: JSON.stringify({
    "grant_type": "client_credentials",
    "audience": "urn:",
    "client_id": "id",
    "client_secret": "secret"
  })

};
request(options, function (error, response) {
  if (error) throw new Error(error);
  console.log(response.body);
});

Answer

request(options, function (error, response, body) {
   if (error) throw new Error(error);
   const stringBodytoJason = JSON.parse(body);
   const token = stringBodytoJason.access_token;
   console.log(token);
}

Leave a Reply

Your email address will not be published. Required fields are marked *