Consider this Express route that expects a JSON body with a name property and responds with a greeting.
app.post('/greet', (req, res) => {
const { name } = req.body;
if (!name) {
return res.status(400).json({ error: 'Name is required' });
}
res.json({ message: `Hello, ${name}!` });
});What will the response be if the client sends { "name": "Alice" } as JSON?
app.post('/greet', (req, res) => { const { name } = req.body; if (!name) { return res.status(400).json({ error: 'Name is required' }); } res.json({ message: `Hello, ${name}!` }); });
Think about what the route does when name is present in the request body.
The route checks if name exists in req.body. If it does, it sends a JSON response with a greeting message including the name. Since the client sends { "name": "Alice" }, the response will be {"message":"Hello, Alice!"}.
You want to validate that the request body contains a username (string) and age (number) before processing it. Which middleware definition is correct?
JSON schema requires type and properties keys with proper types.
Option C correctly defines a JSON schema object with type as 'object', properties specifying types, required fields, and disallows extra properties. Other options misuse types or structure.
Given this route using a JSON schema validator middleware:
app.post('/user', validateSchema(schema), (req, res) => {
res.json({ success: true });
});If the client sends {} (empty body) and schema requires a username, what error will occur?
const schema = {
type: 'object',
properties: {
username: { type: 'string' }
},
required: ['username'],
additionalProperties: false
};Think about how validation middleware handles missing required fields.
The validation middleware detects the missing username and responds with a 400 status and an error message. It does not cause a server error or syntax error.
Consider this route that validates request body against a schema disallowing extra fields:
const schema = {
type: 'object',
properties: {
email: { type: 'string' }
},
required: ['email'],
additionalProperties: false
};
app.post('/subscribe', validateSchema(schema), (req, res) => {
res.json({ subscribed: true });
});If the client sends { "email": "user@example.com", "age": 30 }, what will the response be?
Check what additionalProperties: false means in JSON schema.
The schema forbids any properties not listed in properties. Since age is extra, the validation fails and the middleware returns a 400 error.
Choose the most accurate description of why request and response schemas are used in Express apps.
Think about the purpose of validating data in web applications.
Request and response schemas help verify that data matches expected formats, which prevents errors and security issues. They do not generate forms, replace all error handling, or improve speed by skipping parsing.