Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set the request body via Postman's pre-request script?

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);
});
like image 993
richard Avatar asked Jun 06 '18 08:06

richard


People also ask

How do I send request with body in Postman?

Adding a Request body to the Post request- For this, select the Body tab. Now in the Body tab, select raw and select JSON as the format type from the drop-down menu, as shown in the image below. This is done because we need to send the request in the appropriate format that the server expects.

How do you use a variable from pre-request script in body Postman?

Open a new request tab and enter https://postman-echo.com/get?var={{my_variable}} as the URL. Hover over the variable name to inspect the variable's value and scope. Select Send and send the request. Inspect the response, which confirms that Postman sent the variable value to the API.


2 Answers

Try this.

  body: {
     mode: 'raw',
     raw: JSON.stringify({'loginIdentity': 'admic', 'password': 'abc123'})
  }
like image 143
Chatar Singh Avatar answered Oct 17 '22 03:10

Chatar Singh


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) {
  // ...
});

Postman Javascript API references:

  • Request
  • RequestBody
like image 22
Gino Mempin Avatar answered Oct 17 '22 03:10

Gino Mempin