-1

I'd like to make a POST request on a GET action.

Everything works but I can't see "TOKEN" after the post and I don't understand why.

    var request = require('request');

    exports.getToken = function(req, res){

        var postData = {
            client_id: CLIENT_ID,
            client_secret: CLIENT_SECRET,
            grant_type: 'authorization_code',
            redirect_uri: REDIRECT_URI,
            code: CODE
        }

        request.post({
            uri:"https://api.instagram.com/oauth/access_token",
            form: postData,
            followRedirect: true,
            maxRedirects: 10
        },function(err,res,body){
            var data = JSON.parse(body);
            TOKEN = data.access_token;
        });

        console.log(TOKEN);

        res.render('index', {title: '*****'});
    }
Farid Nouri Neshat
  • 29,438
  • 6
  • 74
  • 115
tonymx227
  • 5,293
  • 16
  • 48
  • 91
  • Your question is not about expressjs, nor nodejs in particular. Your confusion is about asynchronous execution work in javascript: http://stackoverflow.com/questions/7104474/how-does-asynchronous-javascript-execution-happen-and-when-not-to-use-return-st – Farid Nouri Neshat Mar 19 '14 at 14:21
  • There's some reading material for you in here to learn: http://stackoverflow.com/a/9355795/774086 – Farid Nouri Neshat Mar 19 '14 at 15:12

1 Answers1

2

The console.log(TOKEN) is being executed right after the request.post, so you are not giving it time to complete the request. This is the reason for which you provide a callback: a function that will be executed once the request is complete.

Try moving console.log into the callback function and see if you are getting the data there. There are many things you can read to understand asynchronous programming. For instance:

http://callbackhell.com/

http://recurial.com/programming/understanding-callback-functions-in-javascript/

jminuscula
  • 552
  • 2
  • 10
  • Yes if I move console.log into the callback function it works, but I'd like to see TOKEN outside the callback... :/ – tonymx227 Mar 19 '14 at 14:35
  • @tonymx227 not possible as it has not been defined yet. Learn about async and it should all become clear to you. – GiveMeAllYourCats Mar 19 '14 at 14:59
  • Ok so maybe I can send my post differently...? – tonymx227 Mar 19 '14 at 15:48
  • tonymx227 it's not actually a matter of how you send the post. When the post is executed, an asynchronous task is performed and it will necessarily take some time —but while this request is being performed by your browser, the javascript execution continues. That's why you need to provide a callback function, some point for the flow to return when the request is done. – jminuscula Mar 19 '14 at 22:47