Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Leer Creating Custom Middleware | Middleware in Express.js
Express.js Essentials for Backend Development

Creating Custom Middleware

Veeg om het menu te tonen

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:

  1. Define the middleware function, such as checkApiKey, with the parameters req, res, and next;
  2. Inside the function, access the request headers using req.headers['x-api-key'];
  3. If the header is missing, respond with res.status(400).json({ error: 'Missing x-api-key header' }) and return to stop further processing;
  4. If the header is present, call next() to continue to the next middleware or route;
  5. 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.

question mark

Which of the following best describes the process of creating and using a custom middleware function in Express.js?

Selecteer het correcte antwoord

Was alles duidelijk?

Hoe kunnen we het verbeteren?

Bedankt voor je feedback!

Sectie 3. Hoofdstuk 3

Vraag AI

expand

Vraag AI

ChatGPT

Vraag wat u wilt of probeer een van de voorgestelde vragen om onze chat te starten.

Sectie 3. Hoofdstuk 3
some-alt