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

What Is Middleware

Deslize para mostrar o 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?

Selecione a resposta correta

Tudo estava claro?

Como podemos melhorá-lo?

Obrigado pelo seu feedback!

Seção 3. Capítulo 1

Pergunte à IA

expand

Pergunte à IA

ChatGPT

Pergunte o que quiser ou experimente uma das perguntas sugeridas para iniciar nosso bate-papo

Seção 3. Capítulo 1
some-alt