Build HTTP APIs with routing, middleware, validation, controllers, and error handling.
Lessons
Validate request payloads against declarative Joi schemas.
Schema Validation with Joi 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 Schema Validation with Joi example in a small scratch file, then explain what changed and why.