DEV Community

niuniu
niuniu

Posted on

Quick Tip: Node.js Express Middleware

Quick Tip

Node.js Express middleware examples:

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

// Auth middleware
const auth = (req, res, next) => {
  if (!req.headers.authorization) {
    return res.status(401).json({ error: 'Unauthorized' });
  }
  next();
};

// Error handler
app.use((err, req, res, next) => {
  console.error(err.stack);
  res.status(500).json({ error: 'Something broke!' });
});
Enter fullscreen mode Exit fullscreen mode

Powered by MonkeyCode: https://monkeycode-ai.net/

nodejs #javascript #tips

Top comments (0)