Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Postman request body in Pre-request script

Tags:

postman

I have a Postman Pre-request script to add a HMAC key to a request. This works great unless the body has an environment variable in it. So if I have the following body

{
    "key": "{{key}}",
    "value": "some value"
}

When with the key value set to be sample when the request is sent, the body contains the following

{
    "key": "sample",
    "value": "some value"
}

This is what I would expect to happen. However when accessing the request body in the Pre-Request Script,

console.log(pm.request.body.toString());

I get the following

{
    "key": "{{key}}",
    "value": "some value"
}

How can I get the body with the variables having been replaced, so that it is what would be sent to the server?

like image 238
Tanzy Avatar asked Dec 23 '22 20:12

Tanzy


1 Answers

You can interpolate the placeholders using following function:

function interpolate (value) {
    const {Property} = require('postman-collection');
    return Property.replaceSubstitutions(value, pm.variables.toObject());
}

In your case:

console.log(interpolate(pm.request.body.toString()));
like image 128
Peter Walser Avatar answered Jan 14 '23 00:01

Peter Walser