Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Express body-parser req.body with formdata is empty object

Somehow my req.body is always empty, maybe you have an idea:

here is my server code:

const Express = require('express');
const bodyParser = require('body-parser');

const app = new Express();
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

app.post('/save', (req, res) => {
  console.log(req.body)  // => {}
  res.send(req.body);
});

const env = process.env.NODE_ENV || 'production';
app.listen(3000, err => {
   if (err) { return console.error(err); }
   console.info(`Server running on http://localhost:${port} [${env}]`);
});

When I try to send formdata with javascript the req.body is empty:

const data = new FormData(document.querySelector('form'));
console.log(data);  // seems empty already??? FormData{}??
const xhr = new XMLHttpRequest();
xhr.open('POST', 'http://localhost:3000/save');
xhr.send(data);

Same with postman:

postman

I don’t understand this…

Sending x-www-form-urlencoded with postman or raw (application/json) works in postman. But sending the same headers with Formdata in javascript will still result in an empty object…

like image 506
chitzui Avatar asked Jul 01 '17 13:07

chitzui


Video Answer


1 Answers

body-parser is deprecated and isn't a part of Express anymore.

Also, body-parser does not provide the functionality to parse form-data post data.

From the body-parser repository description:

This does not handle multipart bodies, due to their complex and typically large nature. For multipart bodies, you may be interested in the following modules:

  • busboy and connect-busboy
  • multiparty and connect-multiparty
  • formidable
  • multer
like image 148
Achim Krauß Avatar answered Sep 24 '22 09:09

Achim Krauß