postmanlabs / postman-app-support

Postman is an API platform for building and using APIs. Postman simplifies each step of the API lifecycle and streamlines collaboration so you can create better APIs—faster.
https://www.postman.com
5.86k stars 841 forks source link

Postman Pre-request Script Fails to Dynamically Add Header to Request When Setting Value Conditionally #13253

Open Qualizorg opened 1 week ago

Qualizorg commented 1 week ago

Describe the Issue

A pre-request script in Postman is failing to add a header dynamically based on the conditional retrieval of environment variables. The script attempts to add an x-functions-key header by checking for the presence of environment variables x-functions-key and master-x-functions-key. Even though the variables are retrieved and logged correctly, the header does not appear in the request, showing {{x-functions-key}} instead of the expected resolved value.

Pre-request Script Used

var functionsKey = pm.environment.get('x-functions-key');
var masterFunctionsKey = pm.environment.get('master-x-functions-key');

// Log the keys to confirm they are retrieved correctly
console.log("functionsKey:", functionsKey);
console.log("masterFunctionsKey:", masterFunctionsKey);

if (masterFunctionsKey) {
    pm.request.headers.add({ key: 'x-functions-key', value: masterFunctionsKey });
} else if (functionsKey) {
    pm.request.headers.add({ key: 'x-functions-key', value: functionsKey });
} else if (!pm.environment.name.toLowerCase().endsWith("localhost")) {
    throw new Error("Missing x-functions-key in the environment");
}

Expected Behavior

The x-functions-key header should be added to the request with the resolved value from either master-x-functions-key or x-functions-key, based on the pre-request script’s conditional logic.

Actual Behavior

The request header shows {{x-functions-key}} instead of resolving to the actual value added by the pre-request script. This suggests that pm.request.headers.add is not functioning as expected in the pre-request script or that headers added this way are not applied to the outgoing request.

Steps To Reproduce

  1. In the pre-request script, retrieve x-functions-key and master-x-functions-key from the environment.
  2. Use a conditional statement to check which variable is defined and add it to the request headers using pm.request.headers.add.
  3. If neither is defined, throw an error.
  4. Observe the console logs and request headers.

Screenshots or Videos

imagen

Operating System

Windows

Postman Version

11.19.0

Postman Platform

Postman App

User Account Type

Signed In User

Additional Context?

No response