Creating a middleware function is a fundamental aspect of building applications, particularly in frameworks like Express.js for Node.js. 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. They can perform a variety of tasks such as executing code, modifying the request and response objects, ending the request-response cycle, and calling the next middleware function in the stack.
To create a middleware function, you need to define a function that takes three parameters: req, res, and next. The next parameter is a function that you call to pass control to the next middleware function. If you do not call next(), the request will hang and the client will not receive a response.
function myMiddleware(req, res, next) {
// Middleware logic here
console.log('Middleware executed');
// Call the next middleware function
next();
}
Here's an example of a simple logging middleware that logs the request method and URL:
function logger(req, res, next) {
console.log(`${req.method} ${req.url}`);
next();
}
To use the middleware in an Express application, you can register it using the app.use() method. Here’s how you can integrate the logger middleware into an Express app:
const express = require('express');
const app = express();
app.use(logger);
app.get('/', (req, res) => {
res.send('Hello World!');
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
In summary, middleware functions are powerful tools in building robust applications. Understanding how to create and use them effectively is essential for any frontend or backend developer working with frameworks like Express.js.