I'm trying to POST data to my server using the fetch API and every time I do I end up with an empty body.
As far as I can tell from the fetch documentation, to post data you need to pass an object with a method key set to "POST" and a body key with a string or FormData object (or some others).
Here's a simple example that is just not working as I would expect:
var formData = new FormData();
formData.append("test", "woohoo");
formData.append("foo", "bar")
// prints out contents of formData to show that it has contents!
formData.forEach(function(key, value) {
console.log(`${key}: ${value}`);
});
fetch("/fetch", {
method: "POST",
body: formData
}).then(function(response) {
return response.json();
}).then(function(json) {
// Logs empty object
console.log(json);
}).catch(function(err) {
console.log(err);
});
I also have an express server on the back of this that logs the request body and echoes it in the response.
app.post("/fetch", function(req, res) {
// Logs empty object :(
console.log(req.body);
res.send(JSON.stringify(req.body));
});
I add the formData as the body of the fetch request, but nothing ever seems to go through.
throw new TennisBall(), which is all you need for fetch. :)