In ExpressJS, middleware refers to functions that have access to the request and response objects, and can perform certain operations before the request reaches its final destination. Middleware functions can be used to perform tasks such as logging, authentication, and data validation.
Here’s an example of a simple middleware function that logs the current time of each incoming request:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
const express = require('express') const app = express() const logger = (req, res, next) => { console.log(`Time: ${Date.now()}`) next() } app.use(logger) app.get('/', (req, res) => { res.send('Hello World!') }) app.listen(3000, () => { console.log('Example app listening on port 3000!') }) |
In this example, the logger
middleware function is defined to log the current time of each incoming request. The app.use()
method is used to attach the middleware function to the ExpressJS application. When a request is received, the middleware function will be executed before the final destination of the request, and the next()
function is called to pass control to the next middleware function in the chain, or to the final destination of the request.
You can test this middleware function by running the above code and making a request to http://localhost:3000
in your web browser. The current time of the incoming request will be logged in the console.
