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:
JavaScript1function(req, res, next) { 2 // Middleware function code here 3}
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:
JavaScript1var myLogger = function (req, res, next) { 2 req.requestTime = new Date().toLocaleString(); 3 console.log(`Request received at: ${req.requestTime}`); 4 next(); 5};
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:
JavaScript1const axios = require('axios'); 2 3// Function to test a route 4const testRoute = async () => { 5 try { 6 // Put the correct route names instead of "route_name", such as "example" and "api" that were used in this lesson 7 const response = await axios.get('http://localhost:3000/route_name'); 8 console.log(response.data); 9 } catch (error) { 10 console.error(error); 11 } 12}; 13 14// Run the test 15testRoute();
Now that we understand what middleware is, let's see how we can use it in our Express.js
application. First, we need to tell Express.js
to use the middleware function:
JavaScript1var express = require('express'); 2var app = express(); 3 4app.use(myLogger);
This setup runs the myLogger
middleware on every request. To demonstrate its usefulness, we can create a simple route:
JavaScript1app.get('/example', function (req, res) { 2 res.send(`Request received at: ${req.requestTime}`); 3});
When you access /example
, you'll see the request time logged by the middleware and sent back as a response, illustrating how middleware can prepare and manipulate request data. Expect an output similar to:
1Request received at: 8/18/2024, 10:24:58 PM
JSON is a simple format for structuring data that's easy for both humans and machines to read. It's commonly used in web applications to exchange data between a client and a server.
JSON responses are critical in modern web applications for tasks like fetching user information or submitting form data. Now that we've set up middleware, let's move on to handling data with JSON, a cornerstone of web communication.
JSON responses are common in Node.js
servers. Here's how you send JSON data in an Express
app:
JavaScript1app.get('/api', function (req, res) { 2 res.json({ message: `Request received at: ${req.requestTime}` }); 3});
This route sends back a JSON object when accessed. Such responses are essential for enabling seamless communication between the server and client. Expect an output similar to:
1Response from /api endpoint: { message: 'Request received at: 8/18/2024, 10:24:58 PM' }
Middleware and JSON responses work well together. Middleware can modify request and response objects. For instance, prepare a common logging middleware and a route-specific JSON response:
JavaScript1// Middleware function to add request time 2app.use(function (req, res, next) { 3 req.requestTime = Date.now(); 4 console.log(`Request received at: ${req.requestTime}`); 5 next(); 6}); 7 8// Route to send JSON response 9app.get('/api', function (req, res) { 10 res.json({ message: `Request received at: ${req.requestTime}` }); 11});
This middleware logs the request time, and the route sends a JSON response with that time. This demonstrates how middleware prepares data and how JSON responses can be dynamically generated.
Congratulations! You've learned about:
- What middleware is and how it functions in
Express.js
- How to format and send JSON responses
- Combining middleware with JSON responses in an
Express.js
application
Next, you'll have some practice exercises to apply what you've learned. This hands-on practice is key to mastering these concepts. Let's dive in and start practicing!