Q1. How do you handle form data in Express?
For URL-encoded forms (standard HTML forms), use
This parses the data and makes it available in
For multipart forms (file uploads), you need multer or similar middleware.
express.urlencoded({ extended: true }) middleware.This parses the data and makes it available in
req.body.For multipart forms (file uploads), you need multer or similar middleware.
Q2. What's the difference between extended: true and false?
For most cases,
extended: true uses the qs library to parse rich objects and arrays (nested objects).extended: false uses the querystring library, which only supports strings and arrays.For most cases,
true is used for complex form data.Q3. How do you handle file uploads in Express?
Use
Install multer, configure storage, and use it in routes.
Example:
multer middleware.Install multer, configure storage, and use it in routes.
Example:
const upload = multer({ dest: 'uploads/' });
app.post('/upload', upload.single('file'), (req, res) => {
// req.file contains file info
});
Q4. How do you access form data from different input types?
After using the appropriate middleware, all form fields are in
For text inputs, you get string values.
Checkboxes return
Radio buttons return the selected value.
Arrays use name with brackets:
req.body.For text inputs, you get string values.
Checkboxes return
'on' if checked (or the value attribute).Radio buttons return the selected value.
Arrays use name with brackets:
colors[] becomes an array.Q5. What is multipart/form-data and when is it used?
It's required when your form has file inputs.
Express's built-in urlencoded middleware cannot parse this format; you need multer or formidable for multipart data.
multipart/form-data is an encoding type for forms that include files.It's required when your form has file inputs.
Express's built-in urlencoded middleware cannot parse this format; you need multer or formidable for multipart data.
