0
0
Expressframework~30 mins

Validating route params and query in Express - Mini Project: Build & Apply

Choose your learning style9 modes available
Validating route params and query in Express
📖 Scenario: You are building a simple Express server that handles requests for user profiles. Users can request profiles by user ID and optionally filter the profile details by a query parameter.
🎯 Goal: Create an Express route that validates the route parameter userId to be a number and the query parameter details to be either full or summary. If validation passes, respond with a JSON object showing the received parameters.
📋 What You'll Learn
Create an Express app with a GET route at /user/:userId
Validate that userId is a number
Validate that the query parameter details is either full or summary
Send a JSON response with userId and details if valid
Send a 400 status with an error message if validation fails
💡 Why This Matters
🌍 Real World
Validating route and query parameters is essential in web servers to ensure the server receives expected data and can respond correctly without errors.
💼 Career
Backend developers frequently validate parameters in Express routes to build secure and reliable APIs that handle user input safely.
Progress0 / 4 steps
1
Set up Express app and route
Create an Express app by requiring express and calling express(). Then create a GET route at /user/:userId with a callback function that takes req and res parameters.
Express
Need a hint?

Start by importing Express and creating an app instance. Then add a GET route with the exact path /user/:userId.

2
Extract and validate route parameter userId
Inside the route callback, create a variable called userId and assign it the value of req.params.userId. Then create a variable called isUserIdValid that checks if userId converted to a number is not NaN.
Express
Need a hint?

Use req.params.userId to get the route parameter. Use Number() and isNaN() to check if it is a valid number.

3
Extract and validate query parameter details
Create a variable called details and assign it the value of req.query.details. Then create a variable called isDetailsValid that checks if details is either full or summary.
Express
Need a hint?

Use req.query.details to get the query parameter. Check if it equals 'full' or 'summary'.

4
Send response based on validation
Add an if statement that checks if both isUserIdValid and isDetailsValid are true. If so, respond with status 200 and JSON containing userId and details. Otherwise, respond with status 400 and JSON with an error message. Finally, add app.listen(3000) to start the server.
Express
Need a hint?

Use an if to check both validations. Use res.status().json() to send JSON responses. Don't forget to start the server with app.listen(3000).