简体   繁体   中英

Cannot read results from nodejs request result

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

 request({
        url: 'https://graph.facebook.com/v2.6/' + userId + '?fields=first_name,last_name&access_token=' + token,
        method: 'GET', 
    }, function (error, response, body) {
        console.log(error);    
    }).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 data.first_name or data.last_name

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM