简体   繁体   中英

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!

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM