How to access body parameters while using multipart form data in NodeJS

Viewed 2533

There were lots of similar questions related to mine, but no one gonna clear my doubt.

So,whenever I write

<form id="form" action="/" method="post" role="form">

and in my backend code, Let say I write

 console.log(req.body.name)

I got the data correctly, but if I add enctype = multipart/form-data as

<form id="form" action="/" method="post" role="form" enctype="multipart/form-data">

I got req.body.name as 'undefined' or body parameters as 'undefined'.

Is there any way to get the body parameters While using enctype="multipart/form-data? Please Help!

2 Answers

enctype="multipart/form-data" is not natively handled by express, you can use multer to handle multipart/form-data

npm install --save multer

Multer NPM

const multer  = require('multer');
let upload = multer({ dest: 'uploads/' }); //<-- Could be any folder
router.post('/', upload, function (req, res) {
    console.log('Body- ' + JSON.stringify(req.body));
});

In an alternative way, you can use a formidable module from the NPM.

Npm formidable

npm install --save formidable
const multer  = require('formidable');

router.post('/', upload, function (req, res) {
    const form = formidable({ multiples: true });
    form.parse(req, (err, fields, files) => {
      console.log('fields: ', fields);
      console.log('files: ', files);
     // enter code here
    });
});
Related