Reputation: 4050
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
Upvotes: 0
Views: 727
Reputation: 2646
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.
Upvotes: 1
Reputation: 3247
You need to parse the body. To do that you can use the body-parser module
see
https://www.npmjs.com/package/body-parser#examples
Upvotes: 0
Reputation: 1240
I would say it is because the response has not been parsed and is therefor sill a string. Are you using nodes http
module?
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 data = JSON.parse(body);
var name = data.first_name
var message = "Hey there " + name
});
Upvotes: 1