Working with JSON Data and Middleware

Tutorial 3 of 5

1. Introduction

In this tutorial, we'll be discussing how to work with JSON data in Express.js and how to implement middleware to handle various tasks. We'll cover how to parse incoming request bodies in a JSON format and use middleware for tasks like logging and error handling.

By the end of this tutorial, you will be able to:
- Parse JSON data from requests in Express.js
- Implement middleware in Express.js
- Use middleware for logging and error handling

Prerequisites:
- Basic knowledge of JavaScript
- Familiarity with Node.js and Express.js would be helpful

2. Step-by-Step Guide

JSON Data in Express.js

JSON (JavaScript Object Notation) is a popular data format with diverse uses in data interchange, including that of web applications. In Express.js, we can send JSON data using the res.json() function.

res.json({ name: "John", age: 30 });

Middleware in Express.js

Middleware functions are functions that have access to the request object (req), the response object (res), and the next function in the application’s request-response cycle. The next function is a function in the Express router which, when invoked, executes the middleware succeeding the current middleware.

Middleware functions can execute any code, make changes to the request and the response objects, end the request-response cycle, and call the next middleware in the stack.

Using Middleware for Logging and Error Handling

Middleware can be used to log details of every request that gets made to the server, and can also be used to handle errors.

3. Code Examples

Parsing JSON

Express.js has a built-in middleware function, express.json(), to parse incoming request bodies in JSON format.

const express = require('express');
const app = express();

app.use(express.json());

app.post('/', (req, res) => {
  console.log(req.body); // This will log the JSON request body to the console
  res.json(req.body); // This will send the JSON request body as response
});

app.listen(3000, () => console.log('Server started on port 3000'));

Implementing Middleware

This is a simple logging middleware that logs the details of every request made to the server.

app.use((req, res, next) => {
  console.log(`${req.method} request for '${req.url}'`);
  next();
});

This is a simple error handling middleware.

app.use((err, req, res, next) => {
  console.error(err.stack);
  res.status(500).send('Something broke!');
});

4. Summary

In this tutorial, we covered how to parse JSON data from requests in Express.js, how to implement middleware, and how to use middleware for logging and error handling.

To further your learning, you may want to look into:
- More ways to use middleware in Express.js
- How to structure your Express.js applications
- How to handle different types of errors in Express.js

5. Practice Exercises

  1. Create an Express.js server and implement a logging middleware that logs the method and URL of every request made to the server.
  2. Extend the server from the first exercise to send a JSON response containing the details of the request (method and URL) for every GET request made to the server.
  3. Extend the server from the second exercise to implement an error handling middleware that sends a JSON response with a custom error message and the stack trace whenever an error occurs.

Hint: To trigger an error, you can create a route that throws an error, like so:

app.get('/error', (req, res, next) => {
  next(new Error('This is an error'));
});