hwcverwe
hwcverwe

Reputation: 5367

Postman nested variables not parsed in when get environment variable in Pre-Request script

Imagine following environment variables:

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?

Upvotes: 3

Views: 1430

Answers (1)

hwcverwe
hwcverwe

Reputation: 5367

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({
   ....
})

Upvotes: 3

Related Questions