1

I need do a post request with fetch like this in Postman.

And what I've tried :

 let formData = new FormData();
      formData.append('username', String(username));
      formData.append('password', String(password));
  let init = {
    method: 'POST',
    header:{
      'Content-Type': 'application/x-www-form-urlencoded'
    },
   body: formData
}
  fetch(url, init)

It's successful in Postman but failed with fetch that return a 400 error with no param. Hope some helps , thanks

So I changed my code

 var details = {
          'username': '123',
          'password': '123',
      };
      var formBody = [];
      for (var property in details) {
      var encodedKey = encodeURIComponent(property);
      var encodedValue = encodeURIComponent(details[property]);
      formBody.push(encodedKey + "=" + encodedValue);
     }
      formBody = formBody.join("&");

      let init = {
        method: 'POST',
        header:{
          'Accept': 'application/json',
          'Content-Type': 'application/x-www-form-urlencoded'
        },
       body: formBody
    }
      fetch(url, init)

But get a same error

console the formBody:

username=123&password=123

My headers key was wrong ,that was the fault

should be:

let init = {
            method: 'POST',
            headers:{
              'Accept': 'application/json',
              'Content-Type': 'application/x-www-form-urlencoded'
            },
           body: formBody
        }

instead of

let init = {
                method: 'POST',
                header:{
                  'Accept': 'application/json',
                  'Content-Type': 'application/x-www-form-urlencoded'
                },
               body: formBody
            }
Lyle
  • 125
  • 2
  • 13

1 Answers1

0

Status code 400 means you sent a bad request, i.e. the server expected something else.

In this case you're sending raw multipart/form-data (the first option in Postman), while you say you are sending x-www-form-urlencoded in your headers.

Since you'll want to use the latter according to your Postman screenshot, you have to send your body in x-www-form-urlencoded format.

Niels de Bruin
  • 705
  • 5
  • 15
  • How can I format my body in x-www-form-urlencoded ? – Lyle Sep 18 '17 at 09:18
  • How to send your body in x-www-form-urlencoded is a different question, but you'll probably find your answer [here](https://stackoverflow.com/a/37562814/3990318) – Niels de Bruin Sep 18 '17 at 09:27