Middleware in Express.js
The functions used in the request-response cycle known as middleware have access to the request and response object (req, res).
The Express.js routing layer calls many types of Express.js Middleware functions before to the actual request handler. Middleware, as its name suggests, sits between the initial request and the intended ultimate route. The sequence in which middleware functions are added determines how they are always called in stack.
To carry out activities like body parsing for URL-encoded or JSON requests, cookie parsing for fundamental cookie handling, or even dynamically creating JavaScript modules, middleware is frequently utilized.
A middleware function can perform the following tasks:
Middleware for Express.js
The list of middleware that might be utilized in an Express.js app is as follows:
some basic example :
app.use((req, res, next) => {
console.log('Time:', Date.now())
next()
})
app.post('/products', requireJsonContent, (request, response) => {
...
...
response.json(...)
})
app.use((err, req, res, next) => {
console.error(err.stack)
res.status(500).send('Something broke!')
})