We're sorry but this app doesn't work properly without JavaScript enabled. Please enable it to continue.

This lesson's interactive features are locked, please to keep using them

JSON Middleware

Manually parsing the request body with streams is pretty tedious. Luckily, Express has convenient built-in middleware to parse JSON request bodies. All you need is:

import express from "express";

const app = express();

// Built-in JSON body parsing middleware
app.use(express.json());

Express will automatically:

  • Check if the Content-Type header is set to application/json
  • Parse the request into req.body.
  • Handle errors for malformed JSON.
async function handler(req: Request, res: Response) {
  type parameters = {
    body: string;
  };

  // req.body is automatically parsed
  const params: parameters = req.body;
  // ...
}

Assignment

Let's add JSON middleware to our server.

You can re-submit the previous lesson to test your refactored code.