Node.js / Node.js HTTP and Web Servers

Implementing Routing and Middleware

This tutorial will introduce you to the concepts of routing and middleware in Node.js. By the end of this guide, you'll understand how to route users to different parts of your ap…

Tutorial 3 of 5 5 resources in this section

Section overview

5 resources

Explores building web servers and handling HTTP requests with Node.js.

Introduction

In this tutorial, we aim to shed more light on the concepts of routing and middleware in Node.js. Routing refers to how an application's endpoints (URIs) respond to client requests. Middleware, on the other hand, are functions that have access to the request object (req), the response object (res), and the next middleware function in the application’s request-response cycle.

By the end of this tutorial, you'll be able to:
- Understand how routing works in Node.js
- Implement basic routing in your application
- Understand what middleware is and why it's useful
- Implement middleware functions in your application

The prerequisites for this tutorial are basic knowledge of JavaScript, Node.js, and Express.js.

Step-by-Step Guide

Routing

Routing defines how an application responds to a client request to a particular endpoint. For example, a client may send a GET request to the /home endpoint, and we need to define how our application responds to that request.

Let's create a simple route:

app.get('/home', function(req, res) {
  res.send('Welcome to the Home Page!');
});

In this example, we're defining a route for the /home endpoint. When a GET request is made to this endpoint, the function is triggered, sending the string 'Welcome to the Home Page!' back to the client.

Middleware

Middleware functions are functions that have access to the request object, the response object, and the next function in the application's request-response cycle. Here's a basic example:

app.use(function(req, res, next) {
  console.log('Time:', Date.now());
  next();
});

In this example, we're using app.use() to apply a middleware function to every request made to the app. This function simply logs the current time and then calls the next function in the cycle.

Code Examples

Example 1: Basic Routing

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

// define a route handler for the default home page
app.get('/', (req, res) => {
  res.send("Hello, World!");
});

// start the Express server
app.listen(3000, () => {
  console.log("Server is running on port 3000");
});

When we run this code and navigate to http://localhost:3000 in a browser, we should see the text "Hello, World!".

Example 2: Middleware

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

// middleware that logs the time of every request
app.use((req, res, next) => {
  console.log(`Time: ${Date.now()}`);
  next();
});

// route handler for the default home page
app.get('/', (req, res) => {
  res.send('Hello, World!');
});

// start the Express server
app.listen(3000, () => {
  console.log('Server is running on port 3000');
});

Every time a request is made to the server, the middleware function will log the current time to the console before the request is passed on to the route handler.

Summary

In this tutorial, we've learned about routing and middleware in Node.js. We've seen how to define routes to respond to specific client requests, and how to use middleware to add functionality to our application.

For further learning, you might want to look into more complex routing techniques, like parameterised routes and route handlers. For middleware, consider learning more about error-handling middleware and built-in middleware.

Practice Exercises

  1. Create a server with routes for "/about" and "/contact". Each route should respond with a different message.
  2. Implement a middleware function that logs the current date and the requested route every time a request is made.

Here's a possible solution for exercise 1:

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

app.get('/about', (req, res) => {
  res.send('About Page');
});

app.get('/contact', (req, res) => {
  res.send('Contact Page');
});

app.listen(3000, () => {
  console.log('Server is running on port 3000');
});

And here's one for exercise 2:

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

app.use((req, res, next) => {
  console.log(`Date: ${Date.now()} - Route: ${req.path}`);
  next();
});

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

app.listen(3000, () => {
  console.log('Server is running on port 3000');
});

Remember, practice makes perfect. Keep experimenting with different routes and middleware functions to get a good grasp of these concepts!

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

Color Palette Generator

Generate color palettes from images.

Use tool

Open Graph Preview Tool

Preview and test Open Graph meta tags for social media.

Use tool

Watermark Generator

Add watermarks to images easily.

Use tool

AES Encryption/Decryption

Encrypt and decrypt text using AES encryption.

Use tool

Time Zone Converter

Convert time between different time zones.

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