0

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);
});
Ro_Jo
  • 11
  • 1
  • 3
    Does this answer your question? [Javascript how to parse JSON array](https://stackoverflow.com/questions/9991805/javascript-how-to-parse-json-array) – Keimeno Mar 12 '21 at 13:15
  • `JSON.parse()`? – tkausl Mar 12 '21 at 13:16
  • Any Idea how to extract only value of the key "access_token" and use it again in my next from console.log(response.body); – Ro_Jo Mar 12 '21 at 13:23

2 Answers2

0

If you want to get a property from some stringified Json then you can do this, like tkausl suggested.

const obj = {
  auth: '1234',
  notAuth: 'a',
  someField: true
};

const stringified = JSON.stringify(obj);
console.log(stringified);

const auth = JSON.parse(stringified).auth
console.log(auth);
Stefan
  • 160
  • 6
  • So I did as mentioned before. When I run the code it says undefined `request(options, function (error, response) { if (error) throw new Error(error); console.log (response.body); const stringBodytoJason = JSON.stringify(response.body) const token = JSON.parse(stringBodytoJason).access_token console.log(token); ` – Ro_Jo Mar 12 '21 at 14:03
  • I got it fixed. The issue. was (typeof response.body) was a string. So I had to do this to get only the token. ` const token = JSON.parse(response.body).access_token console.log(token); ` Thank you @ps_singh21 and @Stefan – Ro_Jo Mar 12 '21 at 14:30
0
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);
}
ps_singh21
  • 16
  • 2
  • Thank you for this code snippet, which might provide some limited, immediate help. A [proper explanation](https://meta.stackexchange.com/q/114762/9193372) would greatly improve its long-term value by showing why this is a good solution to the problem and would make it more useful to future readers with other, similar questions. Please edit your answer to add some explanation, including the assumptions you’ve made. – Syscall Mar 12 '21 at 14:37