I am setting the access token in my environment variable which will fetch the value from a Pre-request script that I have written and placed in my collection but when I try to run the request it gives me error saying "Message": "Response status code does not indicate success: 401 (Unauthorized)."
but to validate if my token is correct or not I have pasted it directly to the bearer token in the request (took directly from the site) then it works fine. Not sure why in the environment variable it is fetching some different kind of token due to which I am getting this unauthorised error. This token is not matching with the real token when I compared from my site. My request: GET:{{Url}}/api/Ids/
const echoPostRequest = {
url: pm.environment.get('tokenUrl'),
method: 'POST',
header: 'Content-Type:application/x-www-form-urlencoded',
body: {
mode: 'urlencoded',
urlencoded: [
{ key: "id", value: pm.environment.get('Id') }
]
}
};
var getToken = true;
if (!pm.environment.get('accessTokenExpiry') ||
!pm.environment.get('accessToken')) {
console.log('Token or expiry date is missing')
} else if (pm.environment.get('accessTokenExpiry') <= (new Date()).getTime()) {
console.log('Token is expired')
} else {
getToken = false;
console.log('Token and expiry date are all good');
}
if (getToken === true) {
pm.sendRequest(echoPostRequest, function (err, res) {
console.log(err ? err : res.json());
if (err === null) {
console.log('Saving the token and expiry date')
var responseJson = res.json();
pm.environment.set('accessToken', responseJson.access_token)
var expiryDate = new Date();
expiryDate.setSeconds(expiryDate.getSeconds() + responseJson.expires_in);
pm.environment.set('accessTokenExpiry', expiryDate.getTime());
}
});
}
Please suggest.
Thanks in advance.