rksh rksh - 5 months ago 16
Node.js Question

Javascript object returns undefined NodeJs

I'm trying to get Facebook user profile info using the Graph API in nodejs where I am making the following request.

var url = 'https://graph.facebook.com/v2.6/' + id
var qs = {fields:'first_name,last_name',access_token:token}

request({
url: url,
method: 'GET',
qs
}, function(err, response, body){
var name = body.first_name
var message = "Hey there " + name
})
}


The request response from the server looks like this

{
"first_name": "Peter",
"last_name": "Chang"
}


However, the name is returned as undefined. But if I make the call like this.

var url = 'https://graph.facebook.com/v2.6/' + id
var qs = {fields:'first_name,last_name',access_token:token}

request({
url: url,
method: 'GET',
qs
}, function(err, response, body){
var name = body
name = JSON.jsonstringify(body)
var message = "Hey there " + name
})
}


It gives an output like this,

Hey there {"statusCode":200,"body":"{\"first_name\":\"Peter\",\"last_name\":\"Chang\"}"}


So why is the name is returned as undefined in the first example. What am I doing wrong? Please can someone explain. Thanks

Answer

I believe you have to tell request that you're dealing with a JSON response. You can use the json: true property in your request.

request({
  url: url,
  method: 'GET',
  qs,
  json: true
}, function (err, res, body) {
  var name = body.first_name
  var message = "Hey there " + name
});

From the request docs:

json - sets body to JSON representation of value and adds Content-type: application/json header. Additionally, parses the response body as JSON.

Comments