Performance: Validating body fields
This affects server response time and user experience by ensuring only valid data is processed, reducing unnecessary work and errors.
Jump into concepts and practice - no test required
import { body, validationResult } from 'express-validator'; app.post('/submit', [ body('email').isEmail(), body('age').isInt({ min: 0 }) ], (req, res) => { const errors = validationResult(req); if (!errors.isEmpty()) { return res.status(400).json({ errors: errors.array() }); } processData(req.body); res.send('Done'); });
app.post('/submit', (req, res) => { // No validation processData(req.body); res.send('Done'); });
| Pattern | CPU Usage | Response Delay | Error Handling | Verdict |
|---|---|---|---|---|
| No validation | High (processing bad data) | Long (errors cause retries) | Late and costly | [X] Bad |
| Early validation with express-validator | Low (rejects early) | Short (fast error response) | Early and efficient | [OK] Good |
req.body in an Express app?req.body.name is missing?
app.post('/user', (req, res) => {
if (!req.body.name) {
return res.status(400).send('Name is required');
}
res.send(`Hello, ${req.body.name}`);
});app.post('/login', (req, res) => {
if (req.body.username === undefined || req.body.password === undefined) {
res.status(400).send('Missing fields');
}
res.send('Login success');
});req.body.age is a number greater than 18 before processing. Which code snippet correctly validates this and sends a 400 error if invalid?