We use req.body to get the data sent by a user in a web form or API call. It helps the server understand what the user wants to send.
req.body for request payload in Express
app.post('/path', (req, res) => { const data = req.body; // use data here res.send('Got your data'); });
You need to use middleware like express.json() to parse JSON data before accessing req.body.
req.body contains the data sent by the client in the request payload.
app.use(express.json()); app.post('/submit', (req, res) => { console.log(req.body); res.send('Received'); });
app.use(express.urlencoded({ extended: true }));
app.post('/form', (req, res) => {
console.log(req.body.name);
res.send(`Hello, ${req.body.name}`);
});This server listens for POST requests at /greet. It reads the name from req.body and sends a greeting. If no name is sent, it returns an error.
import express from 'express'; const app = express(); const port = 3000; // Middleware to parse JSON body app.use(express.json()); app.post('/greet', (req, res) => { const { name } = req.body; if (name) { res.send(`Hello, ${name}!`); } else { res.status(400).send('Name is missing'); } }); app.listen(port, () => { console.log(`Server running on http://localhost:${port}`); });
Always use express.json() or other body parsers before accessing req.body.
If you forget the middleware, req.body will be undefined.
For security, validate and sanitize data from req.body before using it.
req.body holds the data sent by the client in the request payload.
You must use middleware like express.json() to read JSON data.
Use req.body to get user input from forms or API calls.
Practice
req.body represent in an Express app?Solution
Step 1: Understand the role of
req.bodyreq.bodyholds the data sent by the client inside the request payload, such as form data or JSON.Step 2: Differentiate from other request parts
URL parameters are inreq.params, headers inreq.headers, and response is separate from request.Final Answer:
The data sent by the client in the request payload -> Option AQuick Check:
req.body= client data [OK]
- Confusing
req.bodywith URL parameters - Thinking
req.bodyholds response data - Assuming headers are in
req.body
req.body?Solution
Step 1: Identify middleware for JSON parsing
To parse JSON payloads, Express providesexpress.json()middleware.Step 2: Differentiate from other middleware
express.urlencoded()parses URL-encoded data,express.static()serves files, andexpress.raw()parses raw buffer data.Final Answer:
express.json() -> Option DQuick Check:
JSON parsing middleware = express.json() [OK]
- Using express.urlencoded() for JSON data
- Not adding any middleware before accessing req.body
- Confusing express.static() with body parsing
console.log(req.body) output if the client sends JSON {"name":"Alice","age":30}?
app.post('/user', express.json(), (req, res) => {
console.log(req.body);
res.send('Received');
});Solution
Step 1: Identify the loop range
The route usesexpress.json()middleware, so JSON payload is parsed into an object.Step 2: Understand
Since the client sends JSONreq.bodycontent{"name":"Alice","age":30},req.bodywill be the parsed object with keys and values.Final Answer:
{"name":"Alice","age":30} -> Option CQuick Check:
JSON parsed to object = logged req.body [OK]
- Expecting req.body to be a string
- Forgetting to use express.json() middleware
- Thinking req.body is undefined without middleware
req.body is undefined in this Express app?
const express = require('express');
const app = express();
app.post('/data', (req, res) => {
console.log(req.body);
res.send('Done');
});Solution
Step 1: Identify the loop range
The code does not use any middleware likeexpress.json()orexpress.urlencoded()to parse the request body.Step 2: Understand effect on
Without parsing middleware, Express does not fillreq.bodyreq.body, so it remainsundefined.Final Answer:
Missing middleware to parse the request body -> Option AQuick Check:
No body parser = req.body undefined [OK]
- Assuming route path or method causes undefined body
- Not adding express.json() or express.urlencoded()
- Thinking server listen affects req.body
req.body. Which setup correctly handles both types of payloads?Solution
Step 1: Identify middleware for JSON and URL-encoded data
express.json()parses JSON payloads, andexpress.urlencoded({ extended: true })parses URL-encoded form data.Step 2: Confirm correct order and options
Using both middleware with correct options ensuresreq.bodyworks for both data types.Final Answer:
app.use(express.json()); app.use(express.urlencoded({ extended: true })); -> Option BQuick Check:
Use both json() and urlencoded() middleware [OK]
- Using express.urlencoded() without options
- Mixing middleware order incorrectly
- Using express.static() instead of body parsers
Ready to prove it?
Pass the test and this pattern moves unknown
