Creating Custom Middleware
Scorri per mostrare il menu
When you want your Express.js application to enforce certain rules or perform checks on incoming requests, you can write custom middleware functions. For instance, you might want to ensure that every request includes a specific header before it reaches your route handlers. Below is a custom middleware example that checks for a header called "x-api-key". If the header is missing, the middleware sends a response with a 400 Bad Request status and a message; otherwise, it allows the request to proceed.
function checkApiKey(req, res, next) {
const apiKey = req.headers['x-api-key'];
if (!apiKey) {
return res.status(400).json({ error: 'Missing x-api-key header' });
}
next();
}
This middleware inspects the incoming request’s headers for the "x-api-key". If the header is not present, it immediately stops request processing and sends a JSON error response. If the header exists, it calls next() to pass control to the next middleware or route handler.
To understand how this middleware works and how to use it, follow these steps:
- Define the middleware function, such as
checkApiKey, with the parametersreq,res, andnext; - Inside the function, access the request headers using
req.headers['x-api-key']; - If the header is missing, respond with
res.status(400).json({ error: 'Missing x-api-key header' })and return to stop further processing; - If the header is present, call
next()to continue to the next middleware or route; - Integrate your custom middleware into your Express app by passing it to
app.use()or as a parameter to specific routes:
const express = require('express');
const app = express();
function checkApiKey(req, res, next) {
const apiKey = req.headers['x-api-key'];
if (!apiKey) {
return res.status(400).json({ error: 'Missing x-api-key header' });
}
next();
}
// Apply middleware globally
app.use(checkApiKey);
app.get('/protected', (req, res) => {
res.send('Access granted!');
});
app.listen(3000);
By following these steps, your custom middleware will intercept requests and enforce the presence of the required header before any protected route logic runs.
Grazie per i tuoi commenti!
Chieda ad AI
Chieda ad AI
Chieda pure quello che desidera o provi una delle domande suggerite per iniziare la nostra conversazione