Express.js / Routing in Express.js

Route Parameters

In this tutorial, we will explore the concept of route parameters in Express.js. We will learn how to define dynamic routes and how to capture input from the URL.

Tutorial 3 of 4 4 resources in this section

Section overview

4 resources

Explores handling routes, route parameters, and query strings in Express applications.

1. Introduction

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

2. Step-by-Step Guide

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.

3. Code Examples

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" }.

4. Summary

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.

5. Practice Exercises

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.

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

Lorem Ipsum Generator

Generate placeholder text for web design and mockups.

Use tool

URL Encoder/Decoder

Encode or decode URLs easily for web applications.

Use tool

Meta Tag Analyzer

Analyze and generate meta tags for SEO.

Use tool

Interest/EMI Calculator

Calculate interest and EMI for loans and investments.

Use tool

CSS Minifier & Formatter

Clean and compress CSS files.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help