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

﹥>﹥吖頭↗ 提交于 2019-12-05 15:01:21

To log every field in formData

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 via express use multer. Here is an example - https://www.npmjs.com/package/multer

Make sure to add enctype="multipart/form-data" on 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);
});

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

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

Then in the server code it may 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 already fixed it.

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:

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!