RESTful APIs / Building RESTful APIs with Node.js and Express

Route Management

In this tutorial, you will learn how to manage routing in Express. This will include defining routes, handling parameters, and implementing different request methods.

Tutorial 2 of 4 4 resources in this section

Section overview

4 resources

Explains how to build REST APIs using Node.js and Express framework.

Route Management in Express.js

1. Introduction

Goal

In this tutorial, we will delve into the management of routes in Express.js, a minimal and flexible Node.js web application framework that provides features for web and mobile applications.

Learning Outcomes

By the end of this tutorial, you will be able to:

  • Define routes in Express.js
  • Handle route parameters
  • Implement different HTTP request methods

Prerequisites

  • Basic knowledge of JavaScript
  • Familiarity with Node.js is beneficial, but not compulsory
  • Node.js and NPM (Node Package Manager) installed on your local system

2. Step-by-Step Guide

Defining Routes

Routes refer to how an application responds to a client request for a particular endpoint, which is a URI (or path) and a specific HTTP request method (GET, POST, and so on).

Each route can have one or more handler functions, which are executed when the route is matched.

Here is a basic example:

app.get('/', function (req, res) {
  res.send('Hello World!')
})

Handling Route Parameters

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, with the name of the route parameter specified in the path as their respective keys.

Here's how you can handle route parameters:

app.get('/users/:userId', function (req, res) {
  let userId = req.params.userId;
  res.send('User Id is ' + userId)
})

Implementing Request Methods

Express.js supports methods that correspond to HTTP request methods: get, post, put, delete, etc. Here's an example on how to handle a POST request:

app.post('/users', function (req, res) {
  res.send('Got a POST request at /users')
})

3. Code Examples

Example 1: Basic Route

const express = require('express')
const app = express()

// A route defined for GET request at the homepage
app.get('/', function (req, res) {
  res.send('Welcome to the homepage!')
})

app.listen(3000)

When you run this code and visit 'http://localhost:3000' in your browser, you should see 'Welcome to the homepage!'

Example 2: Route Parameters

const express = require('express')
const app = express()

// Route with a 'name' parameter
app.get('/users/:name', function (req, res) {
  res.send('Hello ' + req.params.name)
})

app.listen(3000)

In this example, if you visit 'http://localhost:3000/users/John', you should see 'Hello John' on the screen.

4. Summary

In this tutorial, we've covered the basics of route management in Express.js, including defining routes, handling route parameters, and implementing different HTTP request methods. For further learning, consider exploring middleware, error handling, and template engines in Express.js.

5. Practice Exercises

  1. Exercise: Create a route that matches the pattern /products/:productId and responds with the product ID.

Solution:
JavaScript app.get('/products/:productId', function (req, res) { res.send('Product ID: ' + req.params.productId) })
Visit 'http://localhost:3000/products/1234' in your browser. You should see 'Product ID: 1234'.

  1. Exercise: Implement a POST request for the route /users.

Solution:
JavaScript app.post('/users', function (req, res) { res.send('Got a POST request at /users') })
You can use Postman or any other API testing tool to send a POST request to 'http://localhost:3000/users'. You should see 'Got a POST request at /users' as the response.

Keep practicing with different routes, request methods, and parameters to get a stronger grasp on Express.js routing.

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

Base64 Encoder/Decoder

Encode and decode Base64 strings.

Use tool

Watermark Generator

Add watermarks to images easily.

Use tool

Fake User Profile Generator

Generate fake user profiles with names, emails, and more.

Use tool

HTML Minifier & Formatter

Minify or beautify HTML code.

Use tool

Lorem Ipsum Generator

Generate placeholder text for web design and mockups.

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