How to use express.urlencoded middleware to process form data in Express
The express.urlencoded()
middleware is used to parse incoming requests with URL-encoded payloads. It is a built-in middleware function in Express. When you use express.urlencoded()
, it parses the URL-encoded data with the qs
library (when extended
is true
) or the querystring
library (when extended
is false
).
Here’s a basic example demonstrating how to use express.urlencoded()
in an Express application:
Step-by-Step Guide
-
Set Up Express Application:
First, create a new Express application if you don't have one already.
-
Use
express.urlencoded()
Middleware:Here’s how you can set up an Express application to use
express.urlencoded()
to handle form submissions or URL-encoded data:const express = require('express'); const app = express(); // Use express.urlencoded() middleware app.use(express.urlencoded({ extended: true })); // Route to display a simple HTML form app.get('/', (req, res) => { res.send(` <form action="/submit" method="post"> <label for="name">Name:</label> <input type="text" id="name" name="name"> <label for="age">Age:</label> <input type="text" id="age" name="age"> <button type="submit">Submit</button> </form> `); }); // Route to handle form submission app.post('/submit', (req, res) => { const name = req.body.name; const age = req.body.age; res.send(`Received the data: Name - ${name}, Age - ${age}`); }); // Start the server const PORT = process.env.PORT || 3000; app.listen(PORT, () => { console.log(`Server is running on http://localhost:${PORT}`); });
-
Explanation:
app.use(express.urlencoded({ extended: true }));
: This middleware parses URL-encoded bodies (as sent by HTML forms) and makes the data available onreq.body
. Theextended: true
option allows for rich objects and arrays to be encoded into the URL-encoded format using theqs
library.- HTML Form: A simple form is created with fields for
name
andage
that submits data to the/submit
route using the POST method. - Handling Form Submission: The
/submit
route handles the POST request. The parsed data is accessible viareq.body
, and the server responds with a message displaying the received data.
Published on: Jun 29, 2024, 04:19 PM