Conteúdo do Curso
Backend Development with Node.js and Express.js
Backend Development with Node.js and Express.js
Middleware
🤔 Understanding Middleware
Middleware allows us to process requests before they reach route handlers. It acts as a filter for incoming requests, providing a way to perform various tasks in the request-response cycle. Middleware functions take three arguments: a request object (req
), a response object (res
), and a next
function, which is used to pass control to the next middleware in the pipeline.
Imagine a water pipe through which water flows. Water is pumped through one end of the pipe and passes through pressure gauges and valves, our middleware, before reaching its destination - our glass. The critical point of this analogy is that the order of these pressure gauges and valves matters.
In the same way, middleware functions in Express.js are executed in a specific order, making the order of middleware registration crucial to the functionality of our application.
🏃♂️ Middleware in Action
Let's embed our own middleware in our app before calling any route.
This function does nothing, it just passes the stream through itself, but our message will always pop up in the console.
This function doesn't perform any specific task; it merely passes the stream through itself. However, it serves to illustrate how middleware works in the Express.js pipeline. In this example, whenever a request is made to our Express.js application, Our middleware
will be logged to the console.
🛤️ Middleware Purpose
Middleware can serve various purposes in an Express.js application, including:
- Logging: Middleware can log request details like the HTTP method, URL, and timestamp, providing insight into the traffic your server is handling;
- Authentication: Middleware can check if a user is authenticated before allowing access to certain routes. This is often used to protect sensitive parts of your application;
- Validation: Middleware can validate request data before processing it. For example, it can check if the data sent in a POST request is in the correct format;
- Error Handling: Middleware can capture and handle errors that occur during request processing. This ensures that your application doesn't crash when unexpected issues arise;
- CORS (Cross-Origin Resource Sharing): Middleware can add CORS headers to responses, allowing or denying requests from different domains. This is essential for securing your APIs and allowing access from web pages hosted on different origins.
Obrigado pelo seu feedback!