Search code examples
jsonpostmanpostman-pre-request-script

Postman: add header in a pre-request script


I have a "pre-request script" in Postman to get the token and add information in a collection variable and it works fine.

I create my request as shown below:

01 const echoPostRequest = {
02   url: pm.collectionVariables.get("token_url"),
03   method: 'POST',
04   header: 'Content-Type:application/json',
05 };

Then later I use pm.sendRequest(echoPostRequest, function (err, res) to submit it and it is working as expected.

Now, I need to replace the single value in header (line 04 in the example above) and add multiple records in the header. I found that I can use pm.request.headers.add, but I'm struggling to find out how to add multiple header parameters within my constant echoPostRequest.

Does anyone know how could it be achieved?

I tried something like:

01 const echoPostRequest = {
02   url: pm.collectionVariables.get("token_url"),
03   method: 'POST',
04   pm.request.headers.add({
05                           'Content-Type':'application/json',
06                           'Authorization':pm.collectionVariables.get("secret")
07                         })
08 };

I tried other formats but none of them worked. I also have collection variables to add in the header.


Solution

  • The header key will accept an object.

    const echoPostRequest = {
        url: pm.collectionVariables.get("token_url"),
        method: 'POST',
        header: {
            "Accept": "application/json",
            "Content-Type": "application/json"
        },
    };