How do I access request body in pre-request test script with values assigned to variables in request body?
right now when I do:
var body = pm.request.body.raw;
console.info(“request body:”+body );
In console I see:
request body:{↵
“ID”: 1,↵
“something”: xyz,↵
“token”: “{{token}}”,↵
“timestamp”: {{unix_timestamp}}↵
So How do I access the request body with actual values assigned to the variables?
I know, I could just do string replace for individual requests. But I have assigned the script to a folder and was expecting it to work for every request in the folder.
Looks like postman… doesn’t resolve the variables … when the request is in pre-requisite tab. I had the same problem and I wrote some javascript function
Usage replaceAllVariables(body).
function replaceAllVariables(str)
{
var totalIndexes=getIndexes(str);
var i=0;
for(i=0;i<totalIndexes.length;i++)
{
str= replaceVariables(str);
}
return str;
}
function getIndexes(str)
{
var a=[],i=-1;
while((i=str.indexOf("{{",i+1)) >= 0) a.push(i);
return a;
}
function replaceVariables(str)
{
var startIndex=str.indexOf("{{");
if(startIndex!==-1)
{
var n = str.indexOf("}}");
var substring=str.substring(startIndex+2,n);
var value=postman.getEnvironmentVariable(substring);
str=str.replace("{{"+substring+"}}",value);
}
return str;
}