0

I am using post man to send a post request with the body as form-data which contains files and text. See the image below:

post request body

I want to json.stringify the entire body but I cannot work out how to do this in a pre-request script. As an environment variable can only be one part of the body further having files makes it more tricky.

Anton James
  • 385
  • 3
  • 6
  • 18

1 Answers1

1

I am not sure I understand the problem. In postman the request is a JavaScript object. If you are trying to stringify the request, I assume you are trying to get this:

propertyOne=valueOne&propertyTwo=ValueTwo

out of this:

const request = {
    propertyOne: 'valueOne',
    propertyTwo: 'ValueTwo'
};

The simple way is just to iterate the object's properties and write into an string:

function stringifyRequest(object) {
    let resultString = '';
    for (var property in object) {
        if (object.hasOwnProperty(property)) {
            let tempString = `${property}=${object[property]}`;
            resultString = resultString ? `${resultString}&${tempString}` : tempString;
        }
    }
    return resultString
}

Now, if you want to get the binary of the file you are uploading, it will not be possible. As seen in this thread:

We don't give access to the contents of the files in pre-request scripts, for a few reasons.

  1. We want to delay loading file contents to right before the request is sent.
  2. The request body is not actually resolved until the pre request scripts are completed. So even if we wanted to we can't give the actual body of the request in pre-request scripts.

They may eventually change that, but I could not find any indications of it. One user in this thread suggests using insomnia, you could check it out if fits your needs better.

Adam
  • 348
  • 2
  • 8