Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Custom Middleware | Express.js Framework
Node.js Express: API & CLI Apps
course content

Conteúdo do Curso

Node.js Express: API & CLI Apps

Node.js Express: API & CLI Apps

1. Introduction
2. Console Applications
3. Express.js Framework
4. Developing REST API

bookCustom Middleware

In Express.js, we can create custom middleware functions using the app.use() method. These functions take three parameters: req (the request object), res (the response object), and next (a function to pass control to the next middleware in the chain). Custom middleware can be applied globally to all routes or specific routes by specifying a route path.

Creating Custom Middleware

Here's a basic example of a custom middleware function that logs the timestamp and URL of every incoming request:

In this example, the custom middleware logs the timestamp and URL of each incoming request to the console. The next() function is called to pass control to the next middleware in the pipeline.

Real-World Example: Combining Built-in and Custom Middleware

Here's a practical example where we use an Express built-in middleware to parse JSON data and then create a custom middleware to validate that data before proceeding:

In this example:

  • We use the built-in middleware express.json() to parse incoming JSON data;
  • We create a custom middleware that checks if the parsed JSON data is missing or empty. If it is, it sends a 400 Bad Request response with an error message. If the data is valid, it calls next() to proceed to the route;
  • The /api/data route expects valid JSON data. If the custom middleware validates the data, the route handler receives it and sends a success response.

This example demonstrates how we can use both built-in and custom middleware to validate data before it reaches our route handlers, ensuring the data is in the expected format before processing it further.

Tudo estava claro?

Como podemos melhorá-lo?

Obrigado pelo seu feedback!

Seção 3. Capítulo 9
some-alt