Topic Overview and Goals

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:

  1. Understand what middleware is and how it functions.
  2. Learn about JSON responses and how to structure them.
  3. See how middleware and JSON can work together in Express.js.

Let's get started!

Understanding Middleware

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:

function(req, res, next) {
  // Middleware function code here
}

Key Points:

  • req: The request object.
  • res: The response object.
  • next: A callback to move to the next middleware function. Without calling next(), 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:

var myLogger = function (req, res, next) {
  req.requestTime = new Date().toLocaleString();
  console.log(`Request received at: ${req.requestTime}`);
  next();
};

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:

const axios = require('axios');

// Function to test a route
const testRoute = async () => {
  try {
    // Put the correct route names instead of "route_name", such as "example" and "api" that were used in this lesson
    const response = await axios.get('http://localhost:3000/route_name');
    console.log(response.data);
  } catch (error) {
    console.error(error);
  }
};

// Run the test
testRoute();
Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal