codex-lv4-may-2025

Level Navigation: 1 2 3 (4ℹ️) (5ℹ️) 6 7 8 9 10 11 12 13 14⚡ 15⚡ (16ℹ️) 17 18 19 20 21 22 23 24 25 26⚡ 27⚡ 28⚡ 29 30 31 32 33 34 35 36 37 38 39⚡ 40⚡

Level 20: Build POST /items

Show Me: POST route starter code

// Make sure you have express.json() middleware set up first!
app.use(express.json());

app.post('/items', (req, res) => {
  // req.body contains the parsed JSON from the request
  const newItem = req.body;
  
  // Add to your storage array
  itemsStorage.push(newItem);
  
  // Return the created item with 201 status
  res.status(201).json(newItem);
});

Diving Deeper: Request Body and Middleware

The request body is the data sent by the client in a POST, PUT, or PATCH request. When you send JSON from Postman or another client, it arrives in the request body as plain text (a string like '{"name":"Alice","age":25}').

Middleware are functions that run between receiving a request and sending a response. They can modify the request or response objects, execute code, or pass control to the next middleware function.

The express.json() middleware transforms that plain text JSON string into a POJO (Plain Old JavaScript Object) that you can use in your code. Without this middleware, req.body would be undefined or contain the raw string.

For JSON request bodies, you need to add express.json() middleware before your routes:

import express from 'express';
const app = express();

// Middleware to parse JSON request bodies
// This transforms the plain text JSON string into a JavaScript object
app.use(express.json());

// Now req.body will contain a parsed JavaScript object
app.post('/items', (req, res) => {
  console.log(req.body); // Access the parsed object (e.g., { name: 'Alice', age: 25 })
  // ...
});

Try It: See What Happens Without Middleware

  1. Temporarily comment out app.use(express.json()) in your server file
  2. Send a POST request from Postman with a JSON body (e.g., { "title": "Test", "price": 10 })
  3. Log req.body in your route handler: console.log('req.body:', req.body)
  4. Observe: You’ll see req.body is undefined because Express hasn’t parsed the JSON string
  5. Uncomment app.use(express.json()) and try again
  6. Now observe: req.body contains the parsed JavaScript object { title: 'Test', price: 10 }

This demonstrates why middleware is essential—it transforms the raw request data into a format your code can work with!