1

A resource is fetched in node.js like this:

requestify.post('myurl')
.then(function (response) {
    console.log(response);
    console.log(response.body);
});

console.log(response) gives:

Response {
    code: 200,
    body: '{"guid":"abcd","nounce":"efgh"}' 
}

console.log(response.body) gives:

{"guid":"abcd","nounce":"efgh"}

However, for some reason I cannot access the key "guid" or "nounce". In both cases I get an undefined. I have tried both with

console.log(response.body.guid);

and

console.log(response.body['guid']);
oderfla
  • 1,695
  • 4
  • 24
  • 49

3 Answers3

1

The body is string, but you want it to be an object. Just transform it:

JSON.parse(response.body).guid
smnbbrv
  • 23,502
  • 9
  • 78
  • 109
1

It seems that the value of body property is a string. You must parse it as JSON:

console.log(JSON.parse(response.body).guid);
kapantzak
  • 11,610
  • 4
  • 39
  • 61
1

You need to set the return type to

response.writeHead(200, {"Content-Type": "application/json"});

so your receiving end will make it an object automagically when received. See Responding with a JSON object in NodeJS (converting object/array to JSON string)

Community
  • 1
  • 1
Tschallacka
  • 27,901
  • 14
  • 88
  • 133