3

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?

hwcverwe
  • 5,287
  • 7
  • 35
  • 63

1 Answers1

3

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({
   ....
})
hwcverwe
  • 5,287
  • 7
  • 35
  • 63
  • 1
    That method should work like this and that was only really implemented to substitute the string values and allow you to use the `{{..}}` syntax in the scripts. `pm.variables.replaceIn("{{Auth-URL}}")` – Danny Dainton Oct 30 '20 at 09:59