What Is Middleware
Veeg om het menu te tonen
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
expressapplication 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.
Bedankt voor je feedback!
Vraag AI
Vraag AI
Vraag wat u wilt of probeer een van de voorgestelde vragen om onze chat te starten.