Consider this Express route that validates the presence of 'username' and 'password' in the request body. What response will the server send if the client sends a POST request with an empty JSON body?
const express = require('express'); const app = express(); app.use(express.json()); app.post('/login', (req, res) => { const { username, password } = req.body; if (!username || !password) { return res.status(400).json({ error: 'Missing username or password' }); } res.status(200).json({ message: 'Login successful' }); });
Think about what happens when required fields are missing in the request body.
The route checks if either 'username' or 'password' is missing. If so, it returns a 400 status with an error message. Since the body is empty, both are missing, so the server responds with status 400 and the error JSON.
Which code snippet correctly checks that the 'email' field exists and is a non-empty string in an Express POST route?
app.post('/subscribe', (req, res) => {
// validation here
});Check both type and content to ensure 'email' is a non-empty string.
Option D checks that 'email' is a string and not just whitespace. Other options either don't check type or can fail if 'email' is undefined.
Look at this Express route snippet. What response will the server send if the client sends a POST request without the 'age' field?
app.post('/profile', (req, res) => { const { age } = req.body; if (age && typeof age === 'number' && age > 0) { res.send('Valid age'); } else { res.status(400).send('Invalid age'); } });
Think about how JavaScript treats undefined in logical AND expressions.
If 'age' is missing, it is undefined, so 'age && ...' is false, causing the else branch to run and respond with 400 status.
Given this Express route, what response will the server send if the client sends { "age": "25" } in the JSON body?
app.post('/check-age', (req, res) => { const { age } = req.body; if (typeof age === 'number' && age >= 18) { res.status(200).json({ message: 'Access granted' }); } else { res.status(403).json({ message: 'Access denied' }); } });
Check the type of 'age' in the condition.
The 'age' field is a string, not a number, so the condition fails and the server responds with 403 and 'Access denied'.
You want to validate that the request body contains 'name', 'email', and 'password' fields before any route handler runs. Which approach below best achieves this in Express?
Think about reusability and centralizing validation logic.
Middleware applied globally can validate requests before reaching route handlers, avoiding repeated code and ensuring consistent validation.