Environment variable does not resolve in pre-request script

Hi,

Looks like environment variables specified as {{env_var}} in URL or request body are NOT resolved before the pre-request script is run.

I am trying to write a pre-request script which will parse the URL to pick up a portion of the URL to be used for encryption/signature. My URL contains an environment variable. During the running of the script, I see that the script picks up the literal string “{{env_var}}” and not the resolved value, and hence the script is failing.

My URL: http://{{my-host}}/resource/{{resource-id}}

My Environment variables which are set:

my-host = localhost:8080
resource-id = 1234

My pre-request script:

 // Grab the request url
 var url = request.url.trim(); 
 console.log("request url = " + url);

I was expecting the console to log http://localhost:8080/resource/1234 , instead it logs http://{{my-host}}/resource/{{resource-id}}

Please advise.

Hey @techierik, the Pre-req script is ran before the request is made.
The variables of the request are resolved only at the run time (when the request is actually been ran).

If your variables are stored in the environment then you can use the pm.environments.get api to access the variables.

Eg:

var myHost = pm.environment.get('my-host');

Also a note that the braces (for eg: {{my-host}}) syntax won’t help you in the test scripts since variables are not resolved in the test scripts using that syntax. You can use the variables api that I mentioned above.

In order to extract some data out of your url, you can perhaps use a regex to extract out the string that you need.
Regex exec docs:

Variables: (Scroll down to accessing variables in scripts)
https://www.getpostman.com/docs/v6/postman/environments_and_globals/variables

More on script execution: https://www.getpostman.com/docs/v6/postman/scripts/intro_to_scripts#execution-order-of-scripts

Sandbox API:
https://www.getpostman.com/docs/v6/postman/scripts/postman_sandbox_api_reference

1 Like