neXus
neXus

Reputation: 2223

In a Postman pre-request-script, how can I read the actual value of a header that uses a variable

I have a variable called token with a specific value myTokenValue

I try to make a call that includes that variable in a header, tokenHeader:{{token}}

I also have a pre-request-script that needs to change the request based on the value of the token header, but if I try to read the value pm.request.headers.get('tokenHeader') I get the literal value {{token}} instead of the interpolated myTokenValue

How do I get this value without having to look at the variable directly?

Upvotes: 0

Views: 6780

Answers (2)

neXus
neXus

Reputation: 2223

Basically I was missing a function to interpolate a string, injecting variables from the environment

There are some workarounds:

function interpolate (value) {
    return value.replace(/{{([^}]+)}}/g, function (match, $1) {
        return pm.variables.get($1);
    });
}
function interpolate (value) {
    const {Property} = require('postman-collection');
    let resolved = Property.replaceSubstitutions(value, pm.variables.toObject());
}

Either of these can be used as
const tokenHeader = interpolate(pm.request.headers.get('tokenHeader'));
but the second one is also null safe.

Upvotes: 1

Peter Walser
Peter Walser

Reputation: 15706

You can use the following function to replace any Postman variables in a string with their resolved values:

var resolveVariables = s => s.replace(/\{\{([^}]+)\}\}/g,  
  (match, capture) => pm.variables.get(capture));

In your example:

var token = resolveVariables(pm.request.headers.get('tokenHeader'));

Upvotes: 2

Related Questions