I'm working on a project with facebook connect in node.js. Everything is working great but now I want to get a list of friends from facebook for the connected user, I have the access token from the user but i don't know how to start getting the data from facebook
Any help?
Working with facebook API from node.js is very easy, create a module (for example: facebook.js
)
facebook.js
var https = require('https');
exports.getFbData = function(accessToken, apiPath, callback) {
var options = {
host: 'graph.facebook.com',
port: 443,
path: apiPath + '?access_token=' + accessToken, //apiPath example: '/me/friends'
method: 'GET'
};
var buffer = ''; //this buffer will be populated with the chunks of the data received from facebook
var request = https.get(options, function(result){
result.setEncoding('utf8');
result.on('data', function(chunk){
buffer += chunk;
});
result.on('end', function(){
callback(buffer);
});
});
request.on('error', function(e){
console.log('error from facebook.getFbData: ' + e.message)
});
request.end();
}
Now, in your code import your facebook module ( var facebook = require('./facebook.js');
) and use it like here:
facebook.getFbData('USER_ACCESS_TOKEN', '/me/friends', function(data){
console.log(data);
});
The getFbData()
is a generic function, you can call it with your api request path (say '/me/friends'), pass the access token
of the current user and a callback function to be called when the data is ready.
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.