Request.data set not working

I’ve tried searching forums here and other places, i can’t seem to find anyone having a similar issue.

request.data=[STRING]
In one context is not updating the payload as expected.

I use this basic structure fairly regularly in relation to hmac generation and variable usage.

var payload= (request.data.length >0)?request.data:"";
payload= payload.replace("{{USERNAME}},pm.variqbles.get(USERNAME));
request.data = payload;

This generally works. I mean it always works in the context of the hmac generation i reference.

However im trying to do the same in a different context, printing payload to the logs i can confirm the string is being updated the way i want but the request.date = payload doesn’t set the body. It just uses what the default was.

Any idea why this would be?

What im trying to achieve is if one variable is one value other fields will be removed from the body. This replace structured seemed like the obvious way to do that but I can’t even force this simplified structure to work.

Any help understanding this will be appreciated. I suspect there’s a gap in my understanding of request.data

Hi @science-physicist-94,

Welcome to the community! :clap:

Sounds like there’s a fairly simple solution for your issue. So you can’t actually update the request body that way. It will always use whats in the “Body” section of the Postman Request. However, you can use an environment variable for the body, such as {{body}} or {{payload}}, and in your pre-request script, you can do all the modification you need to the body. Then at the end, set the body variable like so:

pm.environment.set("payload", payload);
or
pm.environment.set("body", body);

Then, you the request body will actually be updated based on your script.

Hope this is what you’re looking for!

1 Like

Hi @science-physicist-94! Welcome to Postman community :smiley:

As @odanylewycz suggests, request body cannot be modified in script - here is a similar question discussed: Update request.body in pre-request script

Hope this helps!