Middleware in Express.js is a function that is invoked by the Express.js routing layer before the final request handler is executed. Middleware functions can perform a variety of tasks, such as logging requests, validating data, and serving static files.

Example:

const express = require(‘express’);
const app = express();

// Logging middleware
app.use((req, res, next) => {
console.log(`${req.method} request for ${req.url}`);
next();
});

// Serve static files
app.use(express.static(‘public’));

// Handle requests
app.get(‘/’, (req, res) => {
res.send(‘Hello World!’);
});

app.listen(3000);
console.log(‘Express app running on port 3000’);

Leave a Reply

Your email address will not be published. Required fields are marked *