Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't POST data using JavaScript fetch API

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.

Please find my test files in this gist here and help!

like image 908
philnash Avatar asked Apr 21 '26 09:04

philnash


1 Answers

This is because your node server isn't understanding mulitpart forms correctly (which is what FormData) will send by default.

You can use node-muliparty on your server you can read the form easily without touching the frontend code.

Something like:

var multiparty = require('multiparty');
var app = express();

app.post("/fetch", function(req, res) {
  var form = new multiparty.Form();

  form.parse(req, function(err, fields, files) {
    console.log(fields);
    res.send(JSON.stringify(fields));
  });
});

in your index.js will show you it working correctly. There might be a way to make this work with body-parser but I don't know how myself.

like image 116
edds Avatar answered Apr 22 '26 22:04

edds



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!