nikhil.g777
nikhil.g777

Reputation: 904

response body from http get request using request module

I am working on express js and using the request package for http methods

request({
url:'http://custom-url',
method:'GET'},function(err,response,body){

console.log("Got Response : "+respnose.statusCode);
console.log("Body : "+body);
console.log("name is "+body.name);

})


My output is :
Got Response : 200
Body :{"name":"John","id":"139321"}
name is undefined

The body has a name parameter but i don't understand why body.name is undefined, please help !

Upvotes: 0

Views: 836

Answers (1)

abdulbari
abdulbari

Reputation: 6242

Sometimes the response comes in String.

Try to parse it in JSON object then use it

request({
  url: 'http://custom-url',
  method: 'GET'
}, function(err, response, body) {

  if (body && typeof body == "string") {
    body = JSON.parse(body);
  }

  console.log("Got Response : " + respnose.statusCode);
  console.log("Body : " + body);
  console.log("name is " + body.name);

})

Upvotes: 1

Related Questions