Consider this Express.js middleware that validates a JSON request body for a 'username' field:
function validateUser(req, res, next) {
if (!req.body.username) {
return res.status(400).json({ error: 'Username is required' });
}
next();
}What will the server respond if a POST request is sent without the 'username' field?
function validateUser(req, res, next) {
if (!req.body.username) {
return res.status(400).json({ error: 'Username is required' });
}
next();
}Think about what happens when the condition !req.body.username is true.
If the 'username' field is missing, the condition !req.body.username is true, so the middleware sends a 400 status with an error message and does not call next(). This stops further processing.
Given the Joi validation library, which schema correctly requires 'age' to be a number?
const Joi = require('joi');
const schema = Joi.object({
age: ???
});Think about the data type for 'age'.
To validate that 'age' is a number and required, use Joi.number().required(). Other options validate wrong types.
Look at this middleware:
function validate(req, res, next) {
if (req.body.email === undefined || req.body.password === undefined) {
res.status(400).send('Missing fields');
}
next();
}Why might it fail to stop requests missing 'email' or 'password'?
function validate(req, res, next) {
if (req.body.email === undefined || req.body.password === undefined) {
res.status(400).send('Missing fields');
}
next();
}What happens after res.status(400).send() is called?
Calling next() after sending a response causes the request to continue processing, which can lead to unexpected behavior. The middleware should return after sending the response.
Given this code snippet:
const { validationResult, check } = require('express-validator');
app.post('/login', [
check('email').isEmail(),
check('password').isLength({ min: 6 })
], (req, res) => {
const errors = validationResult(req);
res.json({ errors: errors.array() });
});If the request body is { "email": "not-an-email", "password": "123" }, what will be the JSON response?
const { validationResult, check } = require('express-validator');
app.post('/login', [
check('email').isEmail(),
check('password').isLength({ min: 6 })
], (req, res) => {
const errors = validationResult(req);
res.json({ errors: errors.array() });
});Both 'email' and 'password' fail their validations.
The 'email' is not a valid email format and 'password' is shorter than 6 characters, so both produce errors in the array.
Choose the most accurate description of how middleware functions in request validation.
Think about when middleware runs and what it can do with invalid data.
Middleware runs before route handlers and can stop invalid requests early by sending error responses, which helps keep the app secure and efficient.