Middlewares in Express.js in Node.js
Middlewares in Express.js
92
Express is a popular framework for building server-side applications with Node.js. One of the key features of Express is the ability to define middleware functions that can be used in the request-response cycle.
Middleware functions are essentially functions that have access to the request object, the response object, and the next middleware function in the cycle. They can perform various tasks, such as logging, authentication, and error handling, before passing the request to the next middleware function in the chain.
Here’s an example of a simple middleware function that logs each request to the console:
function myLogger(req, res, next) { console.log('Logged:', new Date(), req.url); next(); }
This middleware function can then be used in an Express app by calling app.use()
:
const express = require('express'); const app = express(); app.use(myLogger);
This will cause the myLogger
function to be executed on each request to the server. You can also specify which routes to apply the middleware to by passing a route path as the first argument to app.use()
.
Express comes with several built-in middleware functions, including express.json()
for parsing JSON request bodies and express.static()
for serving static files. Additionally, there are many third-party middleware functions available on npm that can add functionality to your Express app, such as authentication middleware, compression middleware, and caching middleware.
Overall, middleware functions are a powerful feature of Express that enable you to modularize your code and add functionality to your app’s request-response cycle.
March 25, 2023