req.body contain after a POST request?app.use(express.json());
If a client sends a POST request with JSON payload
{"name":"Alice","age":30}, what will req.body contain inside the route handler?app.post('/user', (req, res) => {
res.json(req.body);
});The express.json() middleware parses the incoming JSON payload and converts it into a JavaScript object. This object is then assigned to req.body. So, req.body contains the parsed object, not a string or undefined.
req.body?{"user": {"email": "test@example.com"}}Which option correctly retrieves the email inside the route handler?
app.post('/signup', (req, res) => {
// Access email here
});Option A uses dot notation correctly to access the nested email property. Options A and D are also valid JavaScript, but option A is the simplest and most common way. Option A tries to access a property named 'user.email' which does not exist.
req.body undefined in this Express route?const express = require('express');
const app = express();
app.post('/data', (req, res) => {
res.send(req.body);
});
app.listen(3000);When sending a JSON POST request,
req.body is always undefined. Why?Express does not parse JSON request bodies by default. You must add app.use(express.json()) middleware to parse JSON and populate req.body. Without it, req.body remains undefined.
req.body after sending a form with application/x-www-form-urlencoded?app.use(express.urlencoded({ extended: false }));A client submits a form with fields
username=joe and password=123. What will req.body contain inside the POST route?The express.urlencoded() middleware parses URL-encoded form data and converts it into a JavaScript object assigned to req.body. So req.body will be an object with keys and values from the form.
req.body data directly in Express?req.body before using it?Data in req.body comes from the client and can be manipulated. Without validation or sanitization, this data can lead to security vulnerabilities like SQL injection, cross-site scripting, or server crashes. Always check and clean input before use.