Creating Routes and Middleware in Express

Tutorial 2 of 5

Creating Routes and Middleware in Express

1. Introduction

In this tutorial, we'll delve into the creation of routes and middleware in an Express.js application. Express.js is a popular and robust framework for building web applications on top of Node.js.

The goal here is to equip you with the knowledge needed to define routes that can respond to various HTTP methods and build middleware functions to modify the request and response objects.

You will learn:

  • How to create routes in Express
  • How to create middleware functions in Express

Prerequisites

You should have some basic understanding of:

  • JavaScript
  • Node.js
  • Express.js

2. Step-by-Step Guide

Express Routes

Routes in Express.js define how an application responds to client requests to particular endpoints accessed via HTTP methods.

To define a route, you use app.METHOD(PATH, HANDLER) where:

  • app is an instance of express
  • METHOD is an HTTP request method
  • PATH is a path on the server
  • HANDLER is the function executed when the route is matched

Express Middleware

Middleware functions are functions that have access to the request object, the response object, and the next middleware function in the application's request-response cycle. Middleware functions can:

  • Execute any code
  • Make changes to the request and response objects
  • End the request-response cycle
  • Call the next middleware function in the stack

To create a middleware, you use app.use([path], ...middleware) where:

  • path is optional and defaults to "/"
  • middleware is the middleware function or functions

3. Code Examples

Example 1: Creating a simple route

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

// Route that responds to a GET request at the root '/'
app.get('/', function (req, res) {
  res.send('Hello World!');
});

app.listen(3000, function () {
  console.log('Example app listening on port 3000!');
});
  • express: we import the Express.js module
  • app: we create an instance of Express
  • app.get(...): we define a route that responds to HTTP GET requests
  • app.listen(...): we start the server on port 3000

Example 2: Creating middleware

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

// Middleware function to log request info
app.use((req, res, next) => {
  console.log(`${req.method} request for '${req.url}'`);
  next();
});

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

app.listen(3000, function () {
  console.log('Example app listening on port 3000!');
});
  • app.use(...): we define a middleware function that logs each request's method and URL
  • next(): we call the next middleware function in the stack. If this is omitted, the request will hang

4. Summary

In this tutorial, you've learned how to define routes in an Express app that can respond to different HTTP methods and how to create middleware functions that can modify the request and response objects.

To continue learning, consider exploring:

  • Different types of middleware (application-level, router-level, built-in, error-handling, third-party)
  • More about route parameters and query strings
  • How to organize routes and middleware in larger apps

5. Practice Exercises

Exercise 1

Create a route that responds to POST requests at the path '/data'.

Exercise 2

Create a middleware function that adds a 'timestamp' property to the request object.

Solutions

  1. Route for POST requests:
app.post('/data', function (req, res) {
  res.send('Got a POST request at /data');
});
  1. Middleware function to add a timestamp:
app.use((req, res, next) => {
  req.timestamp = Date.now();
  next();
});

With this middleware, req.timestamp will be available in all following middleware and route handlers.

Keep practicing by adding more routes and middleware to your Express app. Try working with different HTTP methods, paths, and middleware functionality.