Search code examples
node.jsparsingfacebook-graph-apinpm-request

how to parse" http GET request"'s text response in nodejs?


I make a HTTP GET request to Facebook to have a long live token , as a response I have a plain text with the access token and expiration date , but I don't know how to parse it.

request.get('https://graph.facebook.com/oauth/access_token?client_id=' + APP_ID + '&client_secret=' + APP_SECRET + '&grant_type=fb_exchange_token&fb_exchange_token=' + CURRENT_ACCESS_TOKEN)
    .on('data', function(data) {
        console.log("body= " + data); 
    });

res.render('SocialMedia.ejs');

I tried data.access_token but it's undefined


Solution

  • Go through this documentation to get working with the lates 2.8 API (recommended). This will return a JSON response.

    If you want to continue using your API then to parse your response which is in the form of url query params -

    access_token=(the token)&expires=5166486 // data
    

    You can do this -

    var qs = require('qs');
    var response = qs.parse(data); // assuming data is as mentioned above
    console.log(response); // will print {access_token: (the token), expires: 5166486}
    

    Now you can access the token like this -

    response.access_token;