Introduction
Processing forms is a common task when building web applications. In this article, we will learn how to handle forms using Express, a popular web framework for Node.js. By the end, you’ll have a clear understanding of how to extract form data and validate it using Express.
HTML Form Example
Let’s start with an example of an HTML form:
<form method="POST" action="/submit-form">
<input type="text" name="username" />
<input type="submit" />
</form>
When the form is submitted by the user, the browser will automatically make a POST
request to the /submit-form
URL. The form data will be encoded as application/x-www-form-urlencoded
. In our example, the form data will contain the value of the username
input field.
Handling Form Data with Express
To extract and process the form data in Express, we need to use the express.urlencoded()
middleware. This middleware parses the form data and makes it available in the req.body
object. Here’s how you can set it up:
const express = require('express');
const app = express();
app.use(express.urlencoded({ extended: true }));
Make sure to include this middleware before defining any routes that handle form data.
Now, let’s create a POST
endpoint on the /submit-form
route to handle the form submission:
app.post('/submit-form', (req, res) => {
const username = req.body.username;
// Process the form data here...
res.end();
});
In this example, the value of the username
input field can be accessed through req.body.username
.
Validating Form Data
It’s crucial to validate the form data before using it in your application. To simplify the validation process, we can use the express-validator
package. Here’s how to integrate it into our form submission route:
const { body, validationResult } = require('express-validator');
app.post(
'/submit-form',
[
body('username').notEmpty().withMessage('Username is required'),
// Add more validation rules as needed...
],
(req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
// Handle validation errors here...
return res.status(400).json({ errors: errors.array() });
}
// Process the validated form data...
res.end();
}
);
In this example, we use body('username').notEmpty().withMessage('Username is required')
to validate that the username field is not empty. You can add more validation rules as per your requirements.
Conclusion
Handling forms in Express is a fundamental skill for building web applications. By following the steps outlined in this guide, you can process form data, validate it, and ensure a smooth user experience. Remember to sanitize and validate user input to prevent security vulnerabilities in your application.
Tags: Express, forms, form handling, validation, middleware