

0 / 2 embers
0 / 3000 xp
click for more info
Complete a lesson to start your streak
click for more info
Still calibrating
click for more info
Not enough gems
Cost: 6 gems
1: HTTP Clients
incomplete
2: JSON
incomplete
3: JSON Middleware
incomplete
4: The Profane
incomplete
This lesson's interactive features are locked, please to keep using them
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.
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:
'data' events – Each time a chunk of data arrives, append it to your string buffer.'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.
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);
}
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.