Build HTTP APIs with routing, middleware, validation, controllers, and error handling.
Lessons
Trim, escape, and normalize input to prevent injection.
Sanitizing Input is easiest to learn by reading the example, changing it, and observing the result.
// npm install express-validator
import express from 'express';
import { body, validationResult } from 'express-validator';
const app = express();
app.use(express.json());
app.post('/api/users',
body('email').isEmail().normalizeEmail(),
body('password').isLength({ min: 10 }),
(req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(422).json({ errors: errors.array() });
}
res.status(201).json({ created: true });
}
);
app.listen(3000);Practice the Sanitizing Input example in a small scratch file, then explain what changed and why.