Introduction
Sanitization methods clean user input to keep your app safe and working well.
Jump into concepts and practice - no test required
Sanitization methods clean user input to keep your app safe and working well.
body('fieldName').trim().escape()body() or query() from express-validator middleware.trim(), escape(), or normalizeEmail().body('username').trim()body('comment').escape()body('email').normalizeEmail()This Express app cleans user inputs for username, email, and comment using sanitization methods before using them.
import express from 'express'; import { body, validationResult } from 'express-validator'; const app = express(); app.use(express.urlencoded({ extended: true })); app.post('/submit', [ body('username').trim().escape(), body('email').normalizeEmail(), body('comment').trim().escape() ], (req, res) => { const errors = validationResult(req); if (!errors.isEmpty()) { return res.status(400).json({ errors: errors.array() }); } res.send(`Cleaned input:\nUsername: ${req.body.username}\nEmail: ${req.body.email}\nComment: ${req.body.comment}`); }); app.listen(3000, () => console.log('Server running on http://localhost:3000'));
Sanitization helps protect your app from harmful input like scripts or bad data.
Always sanitize inputs before saving or displaying them.
Use libraries like express-validator for easy sanitization in Express.
Sanitization cleans user input to keep apps safe.
Use methods like trim(), escape(), and normalizeEmail().
Sanitize before saving or showing data.
trim() method removes spaces from the start and end of a string.escape() converts special characters, normalizeEmail() formats emails, toLowerCase() changes case.const { body, validationResult } = require('express-validator');
app.post('/submit', [
body('email').normalizeEmail(),
body('username').trim().escape()
], (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
res.send({ email: req.body.email, username: req.body.username });
});{ email: ' USER@Example.COM ', username: ' John ' }app.post('/data', (req, res) => {
req.body.name = req.body.name.trim.escape();
res.send(req.body.name);
});email, username, and bio. Which combination of sanitization methods is best to ensure safe and clean data?normalizeEmail() formats and cleans email addresses correctly.trim() removes extra spaces, escape() prevents harmful HTML or scripts in username and bio.normalizeEmail() for email, trim() and escape() for username, and escape() for bio [OK]