Friday, May 24, 2024
 Popular · Latest · Hot · Upcoming
93
rated 0 times [  95] [ 2]  / answers: 1 / hits: 5785  / 4 Years ago, mon, june 29, 2020, 12:00:00

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", "[email protected]");

// If I do it this way, and assign this to body inside fetch, it works perfectly
// const requestBody = '{"nickname": "johxns","password":"john_password","email":"[email protected]"}';

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.


More From » fetch

 Answers
2

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


[#3338] Friday, June 26, 2020, 4 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
bobbyallanh

Total Points: 693
Total Questions: 120
Total Answers: 101

Location: Bermuda
Member since Thu, Apr 20, 2023
1 Year ago
;