Middleware in Express.js is a function that has access to the request object, response object, and the next middleware function in the application’s request-response cycle. Middleware can be used for tasks such as logging, authentication, and error handling. Example of error-handling middleware:
const express = require('express');
const app = express();
app.use((req, res, next) => {
console.log(`${req.method} ${req.url}`);
next();
});
app.get('/', (req, res) => {
throw new Error('Something went wrong!'); // Simulate an error
});
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).send('Something broke!');
});
app.listen(3000, () => console.log('Server running on http://localhost:3000'));