Hello,
I just started to creat my first scripts in Postman. Im working in Pre-rquest Script.
I can not jump over problem with environment.set function.
- I have a Login method, from this method I need to take a authorization cookie.
- Add this cookie to environment. To let me take it in next request.
- If response code = 200 Send a refresh token method with cookie from response Login method
- Take from response body, accessToken and send it to environment to let use it in main method.
- END off Pre-request script - Send main method request.
The response from the main method is returned with the code 401 - unauthorized. This means that the access token is added to the environment after the main method has been executed. Finally I have to send main request again.
Do you have any ideas how to solve this problem?
var now = new Date();
var expiryTime =
!!pm.environment.get('my_token_expiry_time')
? Date.parse(pm.environment.get('my_token_expiry_time'))
: now;
var difference = Math.floor((now - expiryTime) / 1000);
if (difference > -30) { // if within 30 seconds of expiring
console.log("Old token expired, requesting new one...");
let client = pm.environment.get('client').toString();
let url = pm.environment.get('baseUrl') + "/api/login";
let key = ('auth_' + client);
const PostRequest =
{ url: url,
method: 'POST',
header: {
'Content-Type': 'application/json',
'Accept': 'application/json'
},
body: {
mode: 'raw',
raw: JSON.stringify({
"email": pm.environment.get('email'),
"password": pm.environment.get('password'),
"client": client
})
}};
{pm.sendRequest(PostRequest, function (err,response) {
const jar = pm.cookies.jar()
jar.getAll(url, (error,good) => {
pm.environment.set('my_token_expiry_time', Object.values(good)[1][key].expires)
});
jar.get(url, key, (err, cookies) => {
pm.environment.set('jarget', cookies)
});
if (pm.expect(response).to.have.property('code', 200)) {
let jarget = pm.environment.get('jarget');
let header_Cookie = ('auth_' + client + '=' + jarget);
var url2 = pm.environment.get('baseUrl') + "/api/refresh";
const TokenPostRequest = {
url: url2,
method: 'POST',
header: {
'Content-Type': 'application/json',
'Accept': 'application/json' ,
'Cookie': header_Cookie
},
body: {
mode: 'raw',
raw: JSON.stringify({
"client": client
})
}
};
{pm.sendRequest(TokenPostRequest, function (err, res) {
var response_json = res.json();
var accessToken = response_json.accessToken;
if (pm.expect(response).to.have.property('code', 200)) {
pm.environment.set('token', accessToken)
}
else { console.log(err)};
})}
} else { console.log(err);
}})};
}
I tried to make some delays by timeout funciton but it won’t work as I wish.