Reputation: 1797
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']);
Upvotes: 1
Views: 388
Reputation: 28722
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)
Upvotes: 1
Reputation: 11750
It seems that the value of body
property is a string. You must parse it as JSON:
console.log(JSON.parse(response.body).guid);
Upvotes: 1
Reputation: 24541
The body is string, but you want it to be an object. Just transform it:
JSON.parse(response.body).guid
Upvotes: 1