2

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!

Rajat sharma
  • 31
  • 1
  • 2
  • https://stackoverflow.com/a/63443875/13126651 follow this answer just add middleware to parse your req, `const app = express(); app.use(express.json());` do upvote my answer if it helped you so that it may help others in future – Jatin Mehrotra Sep 25 '20 at 17:38
  • use can use `multer` module, you can access variables using `req.body` and uploaded data from `req.file` or `req.files` depending on single or multiple files – aRvi Sep 25 '20 at 18:01

2 Answers2

2

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));
});
Shivam
  • 3,514
  • 2
  • 13
  • 27
-1

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
    });
});
CyberEternal
  • 2,259
  • 2
  • 12
  • 31