Express.js / REST APIs with Express.js

Working with JSON Data and Middleware

This tutorial will cover working with JSON data in Express.js and implementing middleware to handle various tasks. You'll learn how to parse incoming request bodies in JSON format…

Tutorial 3 of 5 5 resources in this section

Section overview

5 resources

Explores building RESTful APIs using Express.js and best practices for API design.

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'));
});

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

Random Number Generator

Generate random numbers between specified ranges.

Use tool

Image Compressor

Reduce image file sizes while maintaining quality.

Use tool

Age Calculator

Calculate age from date of birth.

Use tool

Color Palette Generator

Generate color palettes from images.

Use tool

Scientific Calculator

Perform advanced math operations.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help