- Express.js Basics
- Express.js HOME
- Express.js Introduction
- Express.js Installation
- Express.js Basic App
- Express.js Routing
- Basics Routing
- Route Parameters
- Handling Query Strings
- Router Middleware
- Middleware
- What is Middleware?
- Application-Level Middleware
- Router-Level Middleware
- Built-In Middleware
- Error-Handling Middleware
- Third-Party Middleware
- Express.js HTTP
- Handling GET Requests
- Handling POST Requests
- Handling PUT Requests
- Handling DELETE Requests
- Templating Engines
- Using Templating Engines
- Setting Up EJS
- Setting Up Handlebars
- Setting Up Pug
- Request/Response
- Request Object
- Response Object
- Handling JSON Data
- Handling Form Data
- Static Files
- Serving Static Files
- Setting Up Static Folders
- Managing Assets
- Express.js Advanced
- Middleware Stack
- CORS in Express.js
- JWT Authentication
- Session Handling
- File Uploads
- Error Handling
- Databases
- Express.js with MongoDB
- MongoDB CRUD Operations
- Express.js with MySQL
- MySQL CRUD Operations
- Deployment
- Deploying Express.js Apps to Heroku
- Deploying Express.js Apps to AWS
- Deploying Express.js Apps to Vercel
Express.js Handling Form Data
Handling form data is essential for many web applications, especially when processing user inputs. Express.js provides easy methods to handle form submissions, both for URL-encoded and multipart form data.
Key Features of Handling Form Data
- Form Data Parsing: Express allows parsing form data, including URL-encoded and multipart form data (file uploads).
- Middleware Support: Express provides built-in middleware and third-party options to handle form data parsing.
- Accessing Form Data: You can access parsed form data through
req.body
for URL-encoded and JSON data.
Components of Handling Form Data
Parsing URL-Encoded Form Data
When a form is submitted with the application/x-www-form-urlencoded
content type (the default for most HTML forms), you can parse the data using the express.urlencoded()
middleware.
Example:
const express = require('express');
const app = express();
// Use express.urlencoded() middleware to parse URL-encoded form data
app.use(express.urlencoded({ extended: true }));
app.post('/submit-form', (req, res) => {
console.log(req.body); // Access parsed form data
res.send('Form data received');
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
In this example, when a POST request with URL-encoded form data is made to /submit-form
, the server parses the data and logs it.
Handling Multipart Form Data (File Uploads)
To handle file uploads and other multipart form data, you need third-party middleware like multer
. Multer
processes multipart/form-data
and stores files on the server.
Example:
const express = require('express');
const multer = require('multer');
const app = express();
// Set up storage for multer
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, 'uploads/');
},
filename: (req, file, cb) => {
cb(null, Date.now() + file.originalname);
}
});
const upload = multer({ storage: storage });
// Route to handle file uploads
app.post('/upload', upload.single('file'), (req, res) => {
console.log(req.file); // Access uploaded file
res.send('File uploaded successfully');
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
In this example, when a file is uploaded through a form with enctype="multipart/form-data"
, multer
handles the parsing and stores the file in the uploads
folder.
Accessing Form Data
Once the form data is parsed, it is available in req.body
for URL-encoded form data, or req.file
for file uploads using multer
.
Example for URL-encoded form:
app.post('/submit', (req, res) => {
const name = req.body.name; // Access name field
const email = req.body.email; // Access email field
res.send(`Received name: ${name}, email: ${email}`);
});
Handling Multiple File Uploads
With multer
, you can also handle multiple file uploads in a single form submission. Use upload.array()
for this.
Example:
app.post('/upload-multiple', upload.array('files', 10), (req, res) => {
console.log(req.files); // Access multiple uploaded files
res.send('Multiple files uploaded successfully');
});
Example Code
const express = require('express');
const multer = require('multer');
const app = express();
// Set up storage for multer
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, 'uploads/');
},
filename: (req, file, cb) => {
cb(null, Date.now() + file.originalname);
}
});
const upload = multer({ storage: storage });
// Use express.urlencoded() middleware to parse URL-encoded form data
app.use(express.urlencoded({ extended: true }));
// Route to handle URL-encoded form data
app.post('/submit-form', (req, res) => {
console.log(req.body); // Access parsed form data
res.send('Form data received');
});
// Route to handle file upload
app.post('/upload', upload.single('file'), (req, res) => {
console.log(req.file); // Access uploaded file
res.send('File uploaded successfully');
});
// Route to handle multiple file uploads
app.post('/upload-multiple', upload.array('files', 10), (req, res) => {
console.log(req.files); // Access multiple uploaded files
res.send('Multiple files uploaded successfully');
});
// Start the server
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
Summary
Express.js provides simple and effective ways to handle both URL-encoded and multipart form data. By using the built-in express.urlencoded()
middleware for URL-encoded data and the third-party multer
middleware for file uploads, you can easily manage form submissions, process form data, and handle file uploads in your applications.