1

I'm currently doing some exercises in order to learn API get/post requests.

I'm making a POST request to http://aq-test.000webhostapp.com/v1/user/new and I have to send this as parameters:

formdata: [
  { "key": "name", "description": "User Name", "type": "text" },
  { "key": "charge", "description": "Position", "type": "text"},
  { "key": "email", "description": "User Email", "type": "text" },
  { "key": "password", "description": "User Password", "type": "text" }
]

I'm doing this request using AngularJS, this way:

var form = new FormData();

form.append('name', 'John Doe');
form.append('charge', 'Dev');
form.append('email', 'x@x.com');
form.append('password', 'pwd');

return $http({
    method: 'POST',
    url: url + 'user/new',
    data: form,
    headers : { 'Content-Type': 'application/x-www-form-urlencoded'}
});

The problem is that, when making this request, the data is sent like this:

[------WebKitFormBoundaryAial7t7Qm5B8KQMv
Content-Disposition:_form-data;_name] => "name"

John Doe
------WebKitFormBoundaryAial7t7Qm5B8KQMv
Content-Disposition: form-data; name="charge"

Dev
------WebKitFormBoundaryAial7t7Qm5B8KQMv
Content-Disposition: form-data; name="email"

x@x.com
------WebKitFormBoundaryAial7t7Qm5B8KQMv
Content-Disposition: form-data; name="password"

pwd
------WebKitFormBoundaryAial7t7Qm5B8KQMv--

And the service answer is: (form field 'name' not valid)

{"status":false,"message":"Campo 'name' no v\u00e1lidoo."}

What am I doing wrong here? PostMan's request body's sent data works flawlessly, and looks different to mine.

[name] => John Doe
[charge] => Dev
[email] => x@x.com
[password] => pwd

What am I missing here? Thanks for taking the time to read my question.

georgeawg
  • 48,608
  • 13
  • 72
  • 95
Klaha
  • 37
  • 8
  • Share with us how is the API expecting the request (does the API provider specifie any guideline for doing requests?). What's different from the Postman request from yours? (headers, etc) – lealceldeiro Aug 10 '18 at 18:14
  • It is wiser to POST data like this as `application/json`. The [FormData API](https://developer.mozilla.org/en-US/docs/Web/API/FormData) should only be used with legacy server APIs. – georgeawg Aug 10 '18 at 18:17
  • 1
    Thanks a lot to @georgeawg, for pointing me in the right direction. I had to set the Content-Type to undefined. – Klaha Aug 10 '18 at 18:23
  • When posting objects created by the [FormData API](https://developer.mozilla.org/en-US/docs/Web/API/FormData), it is important to set the `Content-type` header to `undefined`. – georgeawg Aug 10 '18 at 18:40

0 Answers0