44

I use Postman 6.0 to send an HTTP request. To send a request, I use a pre-request script to get a token and put it into the environment so that it will be used in the succeeding requests.

The script below doesn't work because the body is not sent. Is there anything wrong with the script below?

const getTaxAccessToken={
  url: 'http://dev.xxx.com:4001/api/v1/portal/account/tax-login',
  method: "post",
  body: {
      'loginIdentity': 'admic',
      'password': 'abc123'
  },
  header: {
      'Content-Type': 'application/json'
  }
};
pm.sendRequest(getTaxAccessToken, function (err, response) {
  console.log("get accesstoken");
  console.log(response.access_Token);
  pm.environment.set("taxAccessToken", response.access_Token);
});
Gino Mempin
  • 25,369
  • 29
  • 96
  • 135
richard
  • 1,845
  • 1
  • 20
  • 30

4 Answers4

69

If the request needs to be of type application/x-www-form-urlencoded:

const options = {
  url:  'http://some/url', 
  method: 'POST',
  header: {
    'Accept': '*/*',
    'Content-Type': 'application/x-www-form-urlencoded',
  },
  body: {
    mode: 'urlencoded',
    urlencoded : [
      { key: 'loginIdentity', value: 'admic'},
      { key: 'password', value: 'abc123'},
    ]
  }
};

pm.sendRequest(options, function (err, res) {
  // Use the err and res 
  // ...
  pm.environment.set("my-token", res.json().access_token);
});

Postman Javascript API references:

Gino Mempin
  • 25,369
  • 29
  • 96
  • 135
  • 2
    this is what I was looking for! thank you. I wasn't sure what the different modes are/were for the sendrequest. – Keith E. Truesdell Jun 16 '21 at 20:17
  • Thanks this worked for me. Is there any reference where I can see all valid postman pre-request script example code or document ? – Milan Sep 14 '21 at 13:57
  • 1
    @Milan There are no explicit examples, but I remember going through the Postman API docs for `Request` (http://www.postmanlabs.com/postman-collection/Request.html) and `RequestBody` (http://www.postmanlabs.com/postman-collection/RequestBody.html). – Gino Mempin Sep 14 '21 at 23:41
  • @GinoMempin Thanks RequestBody is intuitive enough. – Milan Sep 15 '21 at 07:56
36

Try this.

  body: {
     mode: 'raw',
     raw: JSON.stringify({'loginIdentity': 'admic', 'password': 'abc123'})
  }
Chatar Singh
  • 943
  • 9
  • 13
11

For Postman >= v8.3.0

With Postman v8.3.0 the update() method was introduced which allows you to set the request body directly from the pre-request script.

For your use case you could simply use:

pm.request.body.update({
    mode: 'raw',
    raw: JSON.stringify({'loginIdentity': 'admic', 'password': 'abc123'})
});

or even shorter:

pm.request.body.update(JSON.stringify({'loginIdentity': 'admic', 'password': 'abc123'}));

Strings, form-data, urlencoded and other Content-Types

As the title is not specifically tailored to JSON request bodies I thought I'd add some examples for how to handle this for other data as many might find this page when searching on Google and run into this issue for other Content-Types.

Raw

raw in Postman expects a string and therefore you can transmit anything that can be expressed as a string e.g. plain text, HTML, XML, JSON etc. .

// plain text
pm.request.body.update(`Hello World!`);
// HTML
pm.request.body.update(`<html>...</html>`);
// XML
pm.request.body.update(`<?xml version="1.0" encoding="UTF-8"?>...`);
// JSON
pm.request.body.update(JSON.stringify({ key: `value` }));

URL-encoded

pm.request.body.update({
    mode: "urlencoded",
    urlencoded: [{
        key: "key",
        value: "value with spaces and special chars ?/ and umlaute öüä"
    }]
});

Form data

pm.request.body.update({
    mode: "formdata",
    formdata: [{
        key: "key",
        value: "value with spaces and special chars ?/ and umlaute öüä"
    }]
});

GraphQL

pm.request.body.update({
    mode: 'graphql',
    graphql: {
        query: `
            query {
                hero {
                    name
                    friends {
                        name
                    }
                }
            }`
    }
});

Example based on GraphQL Tutorial for Fields.

Files from local file system as form-data

pm.request.body.update({
    mode: "formdata",
    formdata: [
        {
            key: "file",  // does not need to be "file"
            type: "file", // MUST be "file"
            src: "/C:/Users/MyUser/Documents/myFile.zip"
        }
    ]
})

Please note: This will only work for files in your current working directory. Otherwise you will receive an error like this Form param 'file', file load error: PPERM: insecure file access outside working directory in the Postman console.

You can see where your working directory is when you go to Settings | General | Working Directory. There also is an option Allow reading files outside working directory which you can enable to read files from anywhere, but be aware that this can allow others to steal data from your computer e.g when you execute untrusted collections.

Postman settings for working directory

Mushroomator
  • 6,516
  • 1
  • 10
  • 27
  • this was so helpful! The `urlencoded` formatting was driving me crazy, and I couldn't find anything in the Postman docs around this. Thanks, friend! – Miguel Vacas Jul 20 '23 at 20:39
1

If you happen to be reading this, and you are looking for a solution to this problem when using MS Dynamics, then here's what I arrived at:

var token = pm.collectionVariables.get("oauth_token");
var expiredRaw = pm.collectionVariables.get("oauth_token_expires");
var fetchToken = (!token || !expiredRaw || (new Date(expiredRaw) < new Date()));
if (!fetchToken) {
    console.log("Not refreshing token");
    return;
}

pm.sendRequest({
      url:  "https://login.microsoftonline.com/common/oauth2/token",
      method: 'POST',
      header: {
        'Accept': 'application/json',
        'Content-Type': 'application/x-www-form-urlencoded',
      },
      body: {
        mode: 'urlencoded',
        urlencoded : [
            { key: 'grant_type', value: 'password'},
            { key: 'client_id', value: pm.environment.get("oauth_client_id")},
            { key: 'client_secret', value: pm.environment.get("oauth_client_secret")},
            { key: 'resource', value: pm.environment.get("oauth_resource")},
            { key: 'username', value: pm.environment.get("oauth_username")},
            { key: 'password', value: pm.environment.get("oauth_password")},
        ]
      }
  }, function (err, res) {
    pm.environment.set("oauth_token", res.json().access_token);
    var expires = new Date();
    var expiresIn = res.json().expires_in ? (+res.json().expires_in) - 10 : 300
    expires.setSeconds(expires.getSeconds() + expiresIn);
    console.log("Logging new expiry", expires);
    pm.collectionVariables.set("oauth_token_expires", expires.toISOString());
});

Just add oauth_token and oauth_token_expires collection variables, make sure you have your credentials in the oauth_* environment variables, paste this into your collection's Pre-request Scripts tab and this will work very nicely.

Andrew Plank
  • 942
  • 10
  • 22