Express body-parser req.body with formdata is an 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 submit 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);

      

The same with the postman:

postman

I do not understand this...

Sending x-www-form-urlencoded

by postal mail or raw (application/json)

working as a postman. But sending the same headers using Formdata in javascript will still result in an empty object ...

+3


source to share


3 answers


Write each field to formData p>

let myForm = document.getElementById('myForm');
formData = new FormData(myForm);

for (let [key, value] of formData.entries()) { 
  console.log(key, value);
}

      

Fiddle - https://jsfiddle.net/thesumit67/j4znhxa5/1/



To handle it with express use multer . Here's an example - https://www.npmjs.com/package/multer

Be sure to add enctype="multipart/form-data"

to the form element. Otherwise Multer will ignore it.

let multer = require('multer');
let upload = multer();

app.post('/save', upload.fields([]), (req, res) => {
  console.log( req.body );
  console.log( req.files );
  res.sendStatus(200);
});

      

+2


source


From what I understand, the problem might be in the HTML form.

<form action="" method="POST">
 <input type="text" name="foo[bar]">
 <button>Submit</button>
</form>

      

Then in server code it might look something like this.



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

      

Again, this post is older, so you've probably fixed it already.

+1


source


body-parser has been deprecated and is no longer part of Express.

In addition, body-parser does not provide functionality to parse form data publication data.

From the body-parser repository description :

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

0


source







All Articles