📖 Scenario: You are building a simple Express server that handles user data. To keep your server organized and safe, you want to define clear rules for what the server expects to receive in requests and what it sends back in responses.
🎯 Goal: Create an Express server with a route /user that accepts a POST request with a JSON body matching a user schema, and responds with a JSON confirming the received data using a response schema.
📋 What You'll Learn
Create an Express app
Define a user data schema for the request body with name (string) and age (number)
Create a POST route /user that validates the request body against the schema
Send a JSON response confirming the received user data
💡 Why This Matters
🌍 Real World
Defining request and response schemas helps keep APIs clear and prevents errors by ensuring data is what the server expects.
💼 Career
Backend developers often define and validate request and response schemas to build reliable and maintainable APIs.
Progress0 / 4 steps
1
Setup Express app and user data schema
Create an Express app by importing express and calling express(). Then create a constant called userSchema that is an object with keys name set to "string" and age set to "number".
Express
Hint
Use require('express') to import Express and call express() to create the app. Define userSchema as an object with the exact keys and string values.
2
Add JSON body parsing middleware
Add middleware to the Express app to parse JSON request bodies by calling app.use(express.json()).
Express
Hint
Use app.use(express.json()) to enable JSON parsing for incoming requests.
3
Create POST /user route with request validation
Create a POST route /user using app.post. Inside the route handler, get req.body and check if name is a string and age is a number. If valid, respond with JSON containing message: "User received" and the user data. If invalid, respond with status 400 and JSON { error: "Invalid user data" }.
Express
Hint
Use app.post('/user', (req, res) => { ... }). Inside, check types with typeof. Send success JSON with res.json or error with res.status(400).json.
4
Start the server on port 3000
Add code to start the Express server listening on port 3000 by calling app.listen(3000).
Express
Hint
Use app.listen(3000) to start the server on port 3000.
Practice
(1/5)
1. What is the main purpose of using request and response schemas in an Express app?
easy
A. To define and validate the shape of data sent and received
B. To speed up the server response time
C. To style the API responses with colors
D. To automatically generate HTML pages
Solution
Step 1: Understand the role of schemas
Request and response schemas specify what data structure is expected, helping to validate inputs and outputs.
Step 2: Identify the main benefit
This validation helps catch errors early and keeps the API clear and consistent.
Final Answer:
To define and validate the shape of data sent and received -> Option A
Quick Check:
Schema purpose = validation [OK]
Hint: Schemas check data shape to avoid errors [OK]
Common Mistakes:
Thinking schemas improve speed directly
Confusing schemas with styling tools
Assuming schemas generate HTML automatically
2. Which of the following is the correct way to use a schema validation middleware in Express for a POST request body?
easy
A. app.get('/user', validateSchema, (req, res) => { ... })
B. app.post('/user', validateSchema, (req, res) => { ... })
C. app.post('/user', (req, res) => validateSchema(req.body))
D. app.use(validateSchema('/user'))
Solution
Step 1: Identify correct HTTP method and middleware usage
Schema validation middleware should be used in the route handler chain, typically for POST requests when validating request bodies.
Step 2: Check syntax correctness
app.post('/user', validateSchema, (req, res) => { ... }) correctly places the middleware function before the route handler for POST '/user'.
A. It does not stop execution after sending 400 response
B. It uses wrong HTTP method for data submission
C. It does not parse JSON body before accessing req.body
D. It sends response twice causing server crash
Solution
Step 1: Check response flow after validation failure
After sending 400 response, the code continues and sends 'Item accepted' response, causing multiple responses.
Step 2: Identify missing control flow
There is no return or else to stop execution after sending error response.
Final Answer:
It does not stop execution after sending 400 response -> Option A
Quick Check:
Send response then stop = return [OK]
Hint: Return after res.send to stop code [OK]
Common Mistakes:
Ignoring missing return after error response
Assuming Express auto-stops after res.send
Confusing HTTP method correctness
5. You want to create an Express route that accepts a JSON body with an array of user objects, each having a required 'email' string and optional 'age' number. Which Joi schema correctly validates this request body?
hard
A. Joi.object({ users: Joi.array().required() })
B. Joi.object({ email: Joi.string().required(), age: Joi.number() }).required()
C. Joi.array().items(Joi.string().email().required())
D. Joi.array().items(Joi.object({ email: Joi.string().email().required(), age: Joi.number() }))
Solution
Step 1: Understand the data shape
The body is an array of user objects, each with required 'email' string and optional 'age' number.
Step 2: Match schema to data shape
Joi.array().items(Joi.object({ email: Joi.string().email().required(), age: Joi.number() })) defines an array of objects with the correct fields and validations.
Final Answer:
Joi.array().items(Joi.object({ email: Joi.string().email().required(), age: Joi.number() })) -> Option D
Quick Check:
Array of objects with required email = A [OK]
Hint: Use array().items(object({...})) for arrays of objects [OK]
Common Mistakes:
Using object schema instead of array for array data
Validating array of strings instead of objects
Missing required email validation
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.