0
0
Expressframework~15 mins

req.params for route parameters in Express - Mini Project: Build & Apply

Choose your learning style9 modes available
Using req.params for Route Parameters in Express
📖 Scenario: You are building a simple Express server that responds to user requests for product details. Each product has a unique ID.
🎯 Goal: Create an Express route that uses req.params to capture the product ID from the URL and send it back in the response.
📋 What You'll Learn
Create an Express app instance called app
Create a route with path /product/:id
Use req.params.id to get the product ID from the URL
Send a response with the text Product ID: <id> where <id> is the captured parameter
💡 Why This Matters
🌍 Real World
Web servers often need to get information from the URL to show specific data, like product details or user profiles.
💼 Career
Understanding how to use route parameters with <code>req.params</code> is essential for backend web development with Express.
Progress0 / 4 steps
1
Set up Express app
Create a variable called express that requires the 'express' module. Then create an Express app instance called app by calling express().
Express
Need a hint?

Use require('express') to import Express and then call it as a function to create the app.

2
Create route with parameter
Use app.get to create a route with path '/product/:id' and a callback function with parameters req and res.
Express
Need a hint?

Use app.get with the path including :id to capture the parameter.

3
Access route parameter
Inside the route callback, create a variable called productId and set it to req.params.id to get the product ID from the URL.
Express
Need a hint?

Use req.params.id to get the value of the :id parameter from the URL.

4
Send response with product ID
Use res.send to send the text `Product ID: ${productId}` as the response inside the route callback.
Express
Need a hint?

Use template literals with backticks to include the productId variable in the response text.