Build HTTP APIs with routing, middleware, validation, controllers, and error handling.
Lessons
Define validation chains and collect field-level errors.
Validating with express-validator 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 Validating with express-validator example in a small scratch file, then explain what changed and why.