Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Apprendre What Is Middleware | Middleware in Express.js
Express.js Essentials for Backend Development

What Is Middleware

Glissez pour afficher le menu

Middleware is a core concept in Express.js that refers to functions which have access to the request and response objects, as well as the next function in the application’s request-response cycle. Middleware functions can perform a range of tasks, such as executing code, modifying the request or response objects, ending the request-response cycle, or passing control to the next middleware function. The execution flow of middleware is sequential: when a request is received, Express.js passes it through each middleware function in the order they are defined until a response is sent or the request is passed to the next handler.

There are several types of middleware in Express.js:

  • Application-level middleware: attached to an instance of the express application and applies to all or specific routes;
  • Router-level middleware: attached to an instance of express.Router() and applies to routes handled by that router;
  • Error-handling middleware: functions with four arguments, used to handle errors that occur in the application.
function logRequest(req, res, next) {
  console.log(req.method, req.url);
  next();
}

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

app.use(logRequest);

app.get('/', (req, res) => {
  res.send('Home page');
});

In this example, the logRequest middleware function receives the request (req), response (res), and next function. It logs the request method and URL, then calls next() to continue to the next middleware or route handler. By using app.use(logRequest), you ensure this middleware runs for every incoming request, demonstrating the sequential and layered flow of middleware in Express.js.

question mark

Which statement best describes middleware in Express.js?

Sélectionnez la réponse correcte

Tout était clair ?

Comment pouvons-nous l'améliorer ?

Merci pour vos commentaires !

Section 3. Chapitre 1

Demandez à l'IA

expand

Demandez à l'IA

ChatGPT

Posez n'importe quelle question ou essayez l'une des questions suggérées pour commencer notre discussion

Section 3. Chapitre 1
some-alt