Node.js
Body parser
Learn body parser middleware with express.json().
Body parser: express.json()
express.json() is a built-in body parser middleware in Express. It automatically parses incoming JSON bodies and puts them in req.body. Usage: app.use(express.json());.
After this middleware is registered, POST routes access the parsed JSON via req.body. Example: app.post("/data", (req, res) => { res.json({ received: req.body.name }); });. If the client sends { "name": "Alex" } then req.body.name is "Alex". If express.json() is not registered, req.body stays undefined. That is why the body parser must be registered before app.post routes.
Reading data with req.body
After express.json() is registered, every POST request's body is available as parsed JSON in req.body. Example: if the client sends { "name": "Alex", "age": 30 }, then req.body.name is "Alex" and req.body.age is 30.
This is the basic way to receive data in APIs. The client sends JSON with a Content-Type: application/json header; Express parses it with express.json(). For the response, res.json(data) automatically adds the Content-Type: application/json header and converts the object to JSON. So request and response flow as JSON in the same format.
Exercise Write a POST route with body parser
Add body parser with app.use(express.json()). Add the route app.post("/data", (req, res) => { res.json({ received: req.body.name }); }). The client sends { name: "Alex" }. The server closes itself.
Show example solution
const express = require("express");
const app = express();
app.use(express.json());
app.post("/data", (req, res) => {
res.json({ received: req.body.name });
});
const server = app.listen(3000, () => {
const http = require("http");
const opts = { hostname: "localhost", port: 3000, path: "/data", method: "POST", headers: { "Content-Type": "application/json" } };
const r = http.request(opts, (res) => {
let body = "";
res.on("data", (c) => body += c);
res.on("end", () => { console.log("Reply: " + body); server.close(); });
});
r.write(JSON.stringify({ name: "Alex" }));
r.end();
});
Test yourself
-
Complete the express.json call
app.use(express.____());
Show answer
app.use(express.json());
-
Match each piece to its role
- express.json()
- Parses JSON body
- req.body
- Parsed data
- app.post
- Defines a POST route
- res.json()
- Sends a JSON response
-
What does express.json() do?
app.use(express.json())
- Renders an HTML template
- Parses JSON bodies into req.body
- Statik dosya sunar
- Redirects the URL
Show answer
Parses JSON bodies into req.body — It parses JSON bodies into req.body.
Next lesson: Summary - Middleware