Hello, learner! Today, we're going to learn about Basic Middleware and JSON Responses in Express.js.
- Middleware: Middleware is a function that runs after a request is received but before a response is sent. Middleware controls the flow of information between the user’s requests and the server’s responses. Middleware is essential for tasks like logging, handling errors, parsing request bodies, and authentication.
- JSON Responses: JSON (JavaScript Object Notation) is a format for structuring data that makes it easy to share between different systems. JSON is critical in modern web applications for exchanging data, such as fetching user information or submitting form data.
Our main objectives today are to:
- Understand what middleware is and how it functions.
- Learn about JSON responses and how to structure them.
- See how middleware and JSON can work together in
Express.js.
Let's get started!
Middleware functions are like traffic controllers for requests and responses. They have access to both the incoming request object (req) and the outgoing response object (res).
Here's a simple definition:
Key Points:
req: The request object.res: The response object.next: A callback to move to the next middleware function. Without callingnext(), the request will not proceed to the following middleware or route handler.
For example, adding a requestTime property to our request object can help with logging and debugging by tracking when a request was made. This can be useful for performance monitoring:
This middleware adds the current date and time to every request received and logs it. The Date().toLocaleString() method converts the date and time to a string, based on the user's local time zone and formatting conventions, making it more readable.
Note: To get the outputs in this lesson, the following Axios-based code was used:
