| 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⚡ |
POST /items201./books, /courses) instead of /items in your routes.POST request:
POST and the URL to http://localhost:3000/items (adjust port as needed).{ "title": "Notebook", "price": 4.99 }.201 with the new record (including any generated id).
// 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);
});
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 })
// ...
});
app.use(express.json()) in your server file{ "title": "Test", "price": 10 })req.body in your route handler: console.log('req.body:', req.body)req.body is undefined because Express hasn’t parsed the JSON stringapp.use(express.json()) and try againreq.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!