Node JS Tutorial - Route Parameters

In this tutorial, we will learn about Route Parameters, which are named URL segments that capture values specified at their position in the URL.

The captured values are populated in the req.params object, with the name of the route parameter specified in the path as their respective keys.

Using Route Parameters

Let's create a route in our project. Open the index.js file and add the following code:


app.get('/users/:username',function(req,res){
var users = {
'user1':{
Name:"jenifer".
Age:25,
Sex:female
},
'user2':{
Name:"John",
Age:28,
Sex:male
}
}
res.render('user',{'user':user[req.params.username]});
});

Next, let's create a view. Inside the views folder, create a new file named user.ejs. Open the user.ejs file and write the following code:


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>User</title>
</head>
<body>
<h1>User Details</h1>
<p><%= user.name ></p>
<p><%= user.age ></p>
<p><%= user.sex ></p>
</body>
</html>

Running the Application

Save all changes and run the application. Switch to the command prompt and run the command:


node index.js

Now, go to the browser and navigate to the URL /users/user1. You should see the details of user1, including name, age, and sex.

If you change the username to /user2, you should see the details of user2.

This is how you can use Route Parameters in Node.js.