Guide to Routing and Middleware in Express

Routing and middleware are two important concepts in Node.js and the Express framework for building web applications.

Routing:

  • Routing is the process of determining how to handle requests from the client and respond with corresponding resources on the server.
  • In Express, we can define routes by specifying the HTTP method (GET, POST, PUT, DELETE, etc.) and the corresponding URL path.
  • Each route can have one or more handler functions to perform tasks such as request processing, database access, and sending responses to the client.

Middleware:

  • Middleware are functions that are executed in a sequence before the request reaches the final route handler.
  • They are used to perform common functionalities and handle intermediate tasks such as authentication, logging, error handling, etc.
  • Middleware can be applied to the entire application or specified for specific routes.
  • Each middleware receives the req (request) and res (response) parameters and can perform processing, pass the request to the next middleware, or end the processing by sending a response to the client.

Example combining Routing and Middleware in Express:

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

// Middleware
const loggerMiddleware = (req, res, next) => {
  console.log('A new request has arrived!');
  next();
};

// Apply middleware to the entire application
app.use(loggerMiddleware);

// Main route
app.get('/', (req, res) => {
  res.send('Welcome to the homepage!');
});

// Another route
app.get('/about', (req, res) => {
  res.send('This is the about page!');
});

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

In this example, we have defined a custom middleware loggerMiddleware to log every new request coming to the server. This middleware is applied to the entire application using the app.use() method. Then, we have defined two routes, one for the main page ('/') and another for the about page ('/about'). Finally, we start the server and listen on port 3000.

The middleware loggerMiddleware will be executed for every request, logging a message to the console before passing the request to the corresponding route handler or middleware in the sequence.

This combination of routing and middleware allows us to handle different requests and perform common tasks efficiently in an Express application.