Reputation: 31
I'm trying to use postman with a Django API and I'm writing some tests for the API. However I'm encountering an issue with postman when run through the console using postman collection run <collection_id>
. I'm using Postman's cookieJar to set and get cookies between requests but I have two of them and it is only adding one when running using the command. This behaviour doesn't happen when run through postman itself.
Here's the test script that runs the code for adding the cookies:
console.log(pm.request)
if (pm.request.url == "http://localhost:8000/api/auth/login/" && pm.request.method == "GET"){
const cookieJar = pm.cookies.jar()
let temp = pm.response.headers;
let temp2 = temp.filter(item => item["key"]=== "Set-Cookie")
let temp3 = temp2[0].value
let temp4 = temp3.slice(10,42)
cookieJar.set("localhost", "csrftoken", temp4);
console.log("Ran tests script")
}
if (pm.request.url == "http://localhost:8000/api/auth/login/" && pm.request.method == "POST"){
const cookieJar = pm.cookies.jar()
pm.response.forEachParent(console.log(pm.response))
let temp5 = pm.response.headers;
let temp6 = temp5.filter(item => item["key"]=== "Set-Cookie")
let temp7 = temp6[0].value
let temp8 = temp6[1].value
let temp9 = temp7.slice(10,42)
let temp10 = temp8.slice(10,42)
console.log(temp9)
console.log(temp10)
cookieJar.set("CLI1", "csrftoken", temp9);
cookieJar.set("CLI2", "sessionid", temp10);
}
The output for the console.logs near the bottom do show that there are values, even when run through the CLI but for some reason the second cookie isn't set because when I retrieve them in the next request with:
cookieJar.getAll("CLI", (error, cookies) => {
if(error){
console.log(error);
}
else {
console.log(cookies)
}
cookieJar.getAll("CLI2", (error, cookies) => {
if(error){
console.log(error);
}
else {
console.log(cookies)
}
})
The output in the CLI command only shows the one array even though I'm logging an array twice, meaning it isn't going into the second cookieJar.getAll. Anyone know what could make this happen?
Upvotes: 0
Views: 175
Reputation: 31
So, after searching around I found the solution: Apparently, you have to do it in the callback of the previous cookie. This also means you can stick to one domain instead of using two cookie domains:
cookies.set("localhost", "csrftoken", csrfcookie, (error) => {
cookies.set("localhost", "sessionid", sesh);
});
This allows postman to correctly set the cookies for the upcoming request when done in the pre-request script.
Upvotes: 0