3

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!

1
  • I believe you're missing throw new TennisBall(), which is all you need for fetch. :) Commented Apr 28, 2016 at 15:18

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.