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!

2
  • 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 Commented Sep 25, 2020 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 Commented Sep 25, 2020 at 18:01

2 Answers 2

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));
});
Sign up to request clarification or add additional context in comments.

Comments

0

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
    });
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.