This tutorial aims to explain the concept of route parameters in Express.js. Route parameters are used to capture dynamic values from the URL. These values can be used inside the route handler to perform certain actions.
By the end of this tutorial, you will learn how to define dynamic routes, capture input from the URL, and use it in your Express.js application.
Prerequisites:
- Basic knowledge of JavaScript
- Basic knowledge of Express.js
Route parameters are named URL segments that are used to capture the values specified at their position in the URL. The captured values are populated in the req.params
object.
Here's how you can define a route with a route parameter:
app.get('/users/:userId', function (req, res) {
res.send(req.params.userId);
})
In the above example, :userId
is a route parameter. You can access its value using req.params.userId
.
Best Practices and Tips:
- Use meaningful names for your route parameters.
- Remember that the order of route definitions matters. Express.js will use the first route or middleware that matches a request.
Example 1: Basic Route Parameter
// Import Express.js
const express = require('express');
// Create an instance of Express.js
const app = express();
// Define a route with a route parameter
app.get('/users/:userId', function (req, res) {
// Send the value of the route parameter
res.send(req.params.userId);
});
// Start the server
app.listen(3000, function () {
console.log('App is listening on port 3000');
});
If you start the server and navigate to http://localhost:3000/users/123
, the server will respond with 123
.
Example 2: Multiple Route Parameters
// Import Express.js
const express = require('express');
// Create an instance of Express.js
const app = express();
// Define a route with multiple route parameters
app.get('/users/:userId/books/:bookId', function (req, res) {
// Send the values of the route parameters
res.send(req.params);
});
// Start the server
app.listen(3000, function () {
console.log('App is listening on port 3000');
});
If you start the server and navigate to http://localhost:3000/users/123/books/456
, the server will respond with { "userId": "123", "bookId": "456" }
.
In this tutorial, we learned how to define dynamic routes and capture input from the URL using route parameters in Express.js.
Next steps for learning could include exploring other types of parameters like query parameters and body parameters.
Exercise 1: Create a route /products/:productId
and send back the product ID.
Solution:
app.get('/products/:productId', function (req, res) {
res.send(req.params.productId);
});
Exercise 2: Create a route /students/:studentId/grades/:gradeId
and send back both the student ID and the grade ID.
Solution:
app.get('/students/:studentId/grades/:gradeId', function (req, res) {
res.send(req.params);
});
Tips for Further Practice:
- Try creating a route with optional route parameters.
- Learn how to validate route parameters using middleware.