1

I have a scenario where I am trying to get the parsed json response of the variable from the below POST request which I want to store in a variable and pass again to the next GET request in the headers. The approach that I am trying now doesn not give the expected results, Is there anything wrong here how should be my approach here to get the expected results, any help is appreciated.

PS : I am new to nodejs

var request = require('request');

var headers = {
    'Accept': 'application/json',
    'Accept-Encoding': 'gzip, deflate',
    'Authorization': 'Basic Y2Y6',
    'Connection': 'keep-alive',
    'Content-Length': '95',
    'User-Agent': 'python-requests/2.22.0',
    'content-type': 'application/x-www-form-urlencoded'
};

var dataString = 'grant_type=password&username=userpp&password=Password';

var options = {
    url: 'https://testurl/oauth/token',
    method: 'POST',
    headers: headers,
    body: dataString
};
let ab;
function callback(error, response, body) {
    if (!error && response.statusCode == 200) {
        //console.log(body);
        var parsedBody = JSON.parse(body)
        //console.log(parsedBody["access_token"])
        ab = parsedBody["access_token"];

    }
}

request(options, callback);

var headers1 = {
    'Accept': 'application/json',
    'content-type': 'application/x-www-form-urlencoded',
    'Authorization': `'bearer ' ${ab}`
};

var options1 = {
    url: 'https://testurl1.com?getdata=user',
    method: 'GET',
    headers: headers1
};

function callback1(error1, response1, body1) {
    if (!error1 && response1.statusCode == 200) {
        console.log(body1);

    }
}

request(options1, callback1);
Thomas
  • 99
  • 2
  • 12
  • try reading more on using callbacks, this answer is a good start https://stackoverflow.com/a/2190872/1245332 – tbonz Dec 19 '19 at 18:11

1 Answers1

0

The problem here is that you're running asynchronous code but treating it synchronously

You see, when you call request(options, callback); and then request(options1, callback1); inline like that, by the time the second request runs, the first callback hasn't happened yet

One way to get around this: put the second request INSIDE the first callback function.

Big brain time: use the request-promise library and learn how to make requests using promises and chaining .then() callbacks.

Humungous brain time: learn how to use async/await features as another nicer way to interact with promises

TKoL
  • 13,158
  • 3
  • 39
  • 73
  • can you share some references on this ? `put the second request INSIDE the first callback function.` How can I do that – Thomas Dec 20 '19 at 03:58
  • @Thomas https://jsfiddle.net/3jehp2mt/ <-- it could be as simple as wrapping your second request inside a function, and calling that function at the appropriate place in the first callback. – TKoL Dec 20 '19 at 09:09
  • I tried this way but it does not executes anything I mean the script is hung for around 10 mins. – Thomas Dec 20 '19 at 10:13
  • Once it goes inside first function whole program goes into hung state. – Thomas Dec 20 '19 at 10:30
  • Have you set any breakpoints to see what's happening? Is your request failing? Is it going into the first 'callback' function at all? – TKoL Dec 20 '19 at 10:54
  • yup I have set the breakpoints as console.log statements where I can see that t`est1, test2, test4` gets printed in console but not `test3`. Here is the updated fiddle https://jsfiddle.net/9jb5wq2L/1/ – Thomas Dec 20 '19 at 15:00
  • You missed out on an important place to check, so I've updated your fiddle: https://jsfiddle.net/gx3o65c2/ Check for the line that says `console.log('inside callback 1');` If it hits that log but not test3, then you probably are getting an error response back. – TKoL Dec 20 '19 at 15:07
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/204615/discussion-between-thomas-and-tkol). – Thomas Dec 20 '19 at 15:11