Imagine following environment variables:
Base-URL
=> https://my.website.com/api
Cars-URL
=> {{Base-URL}}/cars
Auth-URL
=> {{Base-URL}}/login
If I use GET {{Cars-URL}}
in postman it works fine and it does a call to https://mu.website.com/api/cars
Same applies for POST {{Auth-URL}}
it works perfectly and I retrieve a JWT token.
However I would like to use Pre-Request Scripts of my collection to automatically fetch the JWT token before any call in the collection. Therefore I use the following setup:
var authUrl = pm.environment.get("Auth-URL");
pm.sendRequest({
url: authUrl,
method: "POST",
header: { ... },
body: { ... },
function (err, res) {
pm.environment.set("JWT-token", res)
}
});
I get the following output in my console:
POST http://{{base-url}}/login
Error: getaddrinfo ENOTFOUND {{base-url}}
Ocp-Apim-Subscription-Key: xxxxxxxxxxxxxxx
User-Agent: PostmanRuntime/7.26.5
Accept: */*
Postman-Token: xxxxxxxxxxxxxxx
Host: {{base-url}}
Accept-Encoding: gzip, deflate, br
It seems like that pm.environment.get
does not parse the nested variable.
How to fix this issue?
Use pm.variables.replaceIn
(available since v7.6.0.)
This will do the trick:
var authUrl = pm.variables.replaceIn(pm.environment.get("Auth-URL"));
pm.sendRequest({
....
})