Middleware functions can be used for various purposes like logging, authentication, error handling, and more.
Middleware in Node.js refers to functions that have access to the request and response objects and the next middleware function in the application's request-response cycle.
They can execute any code, make changes to the request and response objects, end the request-response cycle, or call the next middleware function in the stack.
Link : https://chat.openai.com/c/e1ac6e22-d68a-4bbe-8e67-9a7686b37386
const express = require('express');
const app = express();
// Logger middleware
const loggerMiddleware = (req, res, next) => {
console.log(`${req.method} ${req.path}`);
next(); // Call the next middleware function
};
// Middleware to parse JSON requests
app.use(express.json());
// Use logger middleware
app.use(loggerMiddleware);
// Route handler
app.get('/', (req, res) => {
res.send('Hello, World!');
});
// Error handling middleware
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).send('Something went wrong!');
});
const PORT = 3000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
© www.thecoderjob.com. All Rights Reserved. Designed by HTML Codex