1

Below is my code which make http request to a web server having host 78.154.17.70, port 8080 and path /csrftoken.json.

I use request.get to get the data from the server. I am able to fetch the data, which is Json data in the following format:

 {
 "apiVersion": "1.0",
 "data": {
       "csrf": "ajbgajbgjabbjbjbab"
  }
}

I declared two variables var CSRFTokenValue; and var respJson; globally. Inside request.get, I use these variables as: respJson store the parse data and CSRFTokenValue store the

"csrf": "ajbgajbgjabbjbjbab" token value as "ajbgajbgjabbjbjbab"

means CSRFTokenValue will store "ajbgajbgjabbjbjbab" in it.

Now when i log CSRFTokenValue inside the request.get it will give me the "ajbgajbgjabbjbjbab" but when I log it outside it will give me undefined .

I need CSRFTokenValue to use in the quesryString inside the request.post to post the data.

I don't know how to get the tokenValue globally??

var request = require('request');

var CSRFTokenValue;
var respJson;
request.get('http://78.154.17.70:8080/csrftoken.json', function (e, res, body){
    respJson = JSON.parse(body);
    CSRFTokenValue = respJson.data.csrf;
    console.log('GET success:' + CSRFTokenValue);
});

console.log('GET token Globaly:' + CSRFTokenValue);

request.post('http://78.154.17.70:8080/Login/post.json?_csrf=' + CSRFTokenValue, {
    'name' : 'name',
    'password' : 'pass'
}, function (res) {
    console.log('success');
});

2 Answers2

3

This is because when you make your initial request it is being done asynchronously. The program moves right to the next statement in your control flow while your request is done in the background. When the request finishes, CSRFTokenValue will be set but you're printing out the value before the request has finished so it's undefined.

Try this instead.

var request = require('request');

request.get('http://78.154.17.70:8080/csrftoken.json', function (e, res, body){
    var respJson = JSON.parse(body);
    var CSRFTokenValue = respJson.data.csrf;
    console.log('GET success:' + CSRFTokenValue);

    request.post('http://78.154.17.70:8080/Login/post.json?_csrf=' +     CSRFTokenValue, {
        'name' : 'name',
        'password' : 'pass'
    }, function (res) {
        console.log('success');
    });
});

This will make your second request once you've gotten the token needed from your first one.

Also, take a look into asynchronous programming.

Cynthia Hart
  • 129
  • 9
0

The line, console.log('GET token Globaly:' + CSRFTokenValue);, would execute immediately, bypassing your asynchronous call, request.get('http://78.154.17.70:8080/csrftoken.json'.... That's the reason CSRFTokenValue is undefined, as in the declaration, you did not initiate it with a value.

Use a promise to run your request.post('http://78.154.17.70:8080/Login/post.json?_csrf='.... Simply run that within request.get when the AJAX call is successful.

BikoMT
  • 51
  • 4