Mefhisto1 Mefhisto1 - 1 year ago 59
Node.js Question

Cannot read results from nodejs request result

I make a request towards FB graph api through node js' request:

url: '' + userId + '?fields=first_name,last_name&access_token=' + token,
method: 'GET',
}, function (error, response, body) {
}).on('response', function (response) {
response.on('data', function (data) {
console.log('user data ' + data); // logs user data {
// "first_name": "Marcus",
// "last_name": "Green" }

var userData = {
firstName: data['first_name'],
lastName: data['last_name']

console.log(userData.firstName) // logs undefined

Same happens when I assign like

Answer Source

If the first call console.log('user data ' + data); returns:

"user data{"first_name":"A","last_name":"B"}"

And not:

"user data[object Object]"

It means, that the data object is a String, not an Object. If you want to use it as an Object and access it's fields, first parse it using:

var parsedData = JSON.parse(data);
console.log(parsedData.first_name); // Logs first_name now