Middleware

Middleware functions are a core feature of Express.js. They can be used to handle requests, modify request and response objects, end requests, and call the next middleware function in the stack.

a. Creating Custom Middleware

Here’s an example of custom middleware that logs the request method and URL:

const logger = (req, res, next) => {
  console.log(`${req.method} ${req.url}`);
  next(); // Call the next middleware or route handler
};

app.use(logger); // Apply middleware globally

b. Error Handling Middleware

In Express, error handling middleware functions have four arguments: err, req, res, and next. Here’s how you can use it:

app.use((err, req, res, next) => {
  console.error(err.stack);
  res.status(500).send('Something went wrong!');
});

Comments

Leave a Reply

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