0

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?

neXus
  • 2,005
  • 3
  • 29
  • 53

2 Answers2

2

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'));
Peter Walser
  • 15,208
  • 4
  • 51
  • 78
1

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.

neXus
  • 2,005
  • 3
  • 29
  • 53