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

Hopefully, by now you already know what JSON is. If not, you should go back and take the Learn HTTP Clients course here first.

What you may be new to is handling and parsing JSON on the server side, rather than sending it as a client.

Decode JSON Request Body

It's very common for POST requests to send JSON data in the request body. Here's how you can handle that incoming data:

{
  "name": "John",
  "age": 30
}

We can manually read this body using Node.js streams. Here's a quick overview of the process:

  1. Initialize a string buffer – this will accumulate the incoming JSON data.
  2. Listen for 'data' events – Each time a chunk of data arrives, append it to your string buffer.
  3. Listen for 'end' events – Once there's no more data coming in, parse your accumulated string as JSON.

For example:

async function handler(req: Request, res: Response) {
  let body = ""; // 1. Initialize

  // 2. Listen for data events
  req.on("data", (chunk) => {
    body += chunk;
  });

  // 3. Listen for end events
  req.on("end", () => {
    try {
      const parsedBody = JSON.parse(body);
      // now you can use `parsedBody` as a JavaScript object
      // ...
    } catch (error) {
      res.status(400).send("Invalid JSON");
    }
  });
}

However, we don't have any guarantees that the incoming JSON will be in the shape we expect. We need to validate the incoming data.

Encode JSON Response Body

Encoding the JSON response is a much simpler process. You just need to stringify the JavaScript object and use the res.send() method.

async function handler(req: Request, res: Response) {
  type responseData = {
    createdAt: string;
    ID: number;
  };

  const respBody: responseData = {
    createdAt: new Date().toISOString(),
    ID: 123,
  };

  res.header("Content-Type", "application/json");
  const body = JSON.stringify(respBody);
  res.status(200).send(body);
}

Assignment

At Chirpy, we have a silly rule that says all Chirps must be 140 characters long or less.

{
  "body": "This is an opinion I need to share with the world"
}
{
  "error": "Something went wrong"
}

For example, if the Chirp is too long respond with a 400 code and this body:

{
  "error": "Chirp is too long"
}
{
  "valid": true
}

Run and submit the CLI tests.