I am trying to check endpoint availability by cascading two api requests and passing first request's response(token) into another in authorization header field. Although the token is getting generated, the second api is not capturing the correct token in the 'token' variable. Let me know scripting error am making. Is there a way to print my authorization field value?
Output of the script is as below:
{
"error": "Invalid token."
}
401
AssertionError [ERR_ASSERTION]: Expected 200 response
Code:
var assert = require('assert');
var request = require('request');
var options2,token,info;
var options = {
'method': 'POST',
'url': '1',
'headers': {
'Content-Type': 'application/x-www-form-urlencoded'
},
form: {
'client_id': '*',
'client_secret': '**',
'grant_type': 'client_credentials'
}
};
request(options, function (error, response) {
if (error) throw new Error(error);
info = JSON.parse(response.body);
console.log(info.access_token);
token=info.access_token;
});
var request = require('request');
var options2 = {
'method': 'GET',
'url': '***',
'headers': {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' token,
}
};
request(options2, function (error, response) {
if (error) throw new Error(error);
console.log(response.body);
console.log(response.statusCode);
assert.ok(response.statusCode == 200, 'Expected 200 response');
});
CodePudding user response:
Move the call
request(options2, function (error, response)
,
inside the callback function of request 1, along with options2.
Since request 1 call (token one) can take some time your request 2 will be fired while you still haven't received response for token call. You can also use Async/Await to make it more clear, since callbacks makes things hard to read.