3

I read all over but couldn't find the answer.

When I use FormData(), it returns status 404 bad request.

However, if I pass the data (hardcoded) as in const requestBody (example below), it works perfectly.

This is my code:

    var formData = new FormData();
    formData.append("nickname", "johxns");
    formData.append("password", "john_password");
    formData.append("email", "john@server.com");

    // If I do it this way, and assign this to body inside fetch, it works perfectly
    // const requestBody = '{"nickname": "johxns","password":"john_password","email":"john@server.com"}';

    fetch("http://localhost:5000/create_user", {
        // if instead of formData, I assign requestBody to body, it works!
        body: formData,
        headers: {
            "Content-Type": "application/json"
        },
        method: "POST"
    }).then(function(response) {
        return response.text();
    }).then(function(data){
        console.log('data', data);
    }).catch(function(err){
        console.err(err);
    });

I already tried with URLSearchParams, but still couldn't make it work.

Thanks.

JohnBonjon
  • 73
  • 1
  • 6

2 Answers2

7

You shouldn't set the Content-Type header to application/json if you're not sending json. According to this answer, you don't need to set the Content-Type header.

body data type must match "Content-Type" header

Using Fetch

Shoejep
  • 4,414
  • 4
  • 22
  • 26
0

You should either send json data if you set Content-Type to application/json or not set any Content-Type if using FormData API since the fetch function is able to determine the correct Content-Type.

See here for more informations.

Martial Anouman
  • 381
  • 1
  • 10