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

What Is Middleware

Svep för att visa menyn

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?

Vänligen välj det korrekta svaret

Var allt tydligt?

Hur kan vi förbättra det?

Tack för dina kommentarer!

Avsnitt 3. Kapitel 1

Fråga AI

expand

Fråga AI

ChatGPT

Fråga vad du vill eller prova någon av de föreslagna frågorna för att starta vårt samtal

Avsnitt 3. Kapitel 1
some-alt