Repository navigation
Reading 08
Middleware functions are functions that have access to the request object (req), the response object (res), and the next middleware function in the application’s request-response cycle. Middleware functions can perform the following tasks:
Execute any code. Make changes to the request and the response objects. End the request-response cycle. Call the next middleware function in the stack.
An Express application can use the following types of middleware:
Application-level middleware Router-level middleware Error-handling middleware Built-in middleware Third-party middleware
Bind application-level middleware to an instance of the app object by using the app.use() and app.METHOD() functions, where METHOD is the HTTP method of the request that the middleware function handles (such as GET, PUT, or POST) in lowercase.
Route handlers enable you to define multiple routes for a path.
Here is an example of loading a series of middleware functions at a mount point, with a mount path. It illustrates a middleware sub-stack that prints request info for any type of HTTP request to the /user/:id path.
app.use('/user/:id', function (req, res, next) { console.log('Request URL:', req.originalUrl) next() }, function (req, res, next) { console.log('Request Type:', req.method) next() })