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}}
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:
How can request signature be computed in pre-request script? Value will be invalid because of unresolved env variables. Is there a more elegant way than resolve {{}} manually?
Not sure if youβre still looking for an answer. I had a similar issue while trying to use collection variable defined at the collection level inside a pre-request script which is also defined at collection level.
Below variable assignment inside the script worked for me. const var_name = pm.variables.get('var_name');
In our scenario, we had to generate an hmac signature which required the url and body as input. Below is our solution which we put in the βpre-request scriptβ tab of the root folder:
/**
* Takes unrealized template of a URL or Body, and returns a realized version with values.
* @param {string} template
*/
function realize(template) {
const rgx = /{{[a-z|A-Z|0-9]*}}/gm;
const matches = [...template.matchAll(rgx)];
matches.forEach((match) => {
template = template.replace(
match[0],
pm.environment.get(match[0].substring(2, match[0].length - 2))
);
});
return template;
}
/****** USAGE *******/
const url = realize(pm.request.url.toString());
const body = realize(pm.request.body..toString());
pm.environment.set('signature', generateSignature(url, body));