I am working with a node.js application that uses Facebook APIs. In one part of my code I need to return the access_token from a common function. That is, a lot of other functions need to call this function to retrieve the Facebook access token.
Below is my code:
function getAccesstoken(code) {
var options = {
host: 'graph.facebook.com',
path: '/oauth/access_token?client_id=xxxx&redirect_uri=xxxxxx&client_secret=xxxxx&code='+code.toString()
};
var acc_token = ''
https.get(options, function(resp) {
resp.on('data', function(d) {
acc_token = acc_token+d.toString()
});
resp.on('end', function() {
var expiry_index = acc_token.indexOf('&expires=')
acc_token = acc_token.substring(0, expiry_index)
});
});
return acc_token.toString()
}
Since https.get call is asynchronous, function always returns an empty string. What should be the best way to do this?
well supply a callback function to your getAccesToken function and call the function after the response has ended and pass acc_token to that function..
then call your function like