Process JSON payloads
A client sends JSON to a POST endpoint and the server needs to read submitted fields.
Express.js · Const
req.body is the parsed key-value data submitted in an HTTP request body. Express fills it through compatible body-parsing middleware such as express.json() or express.urlencoded(); otherwise it is undefined.
req.body exposes the key-value data submitted in an HTTP request body after compatible body-parsing middleware has processed it. Without such middleware, its value is undefined; because the contents come from the user, validate them before use.
req.bodyreq.body inside handlers.const express = require('express');
const app = express();
app.use(express.json());
app.post('/profile', (req, res) => {
const name = typeof req.body?.name === 'string' ? req.body.name : '';
res.json({ name });
});
app.listen(3000);JSON middleware parses matching requests before the route reads the submitted fields.
A client sends JSON to a POST endpoint and the server needs to read submitted fields.
An HTML form submits URL-encoded values that a route must consume.
An endpoint receives client-controlled data that must be checked before persistence or business logic.
req.body in Express, and how is it populated?req.body is an object containing key-value pairs submitted in the request body. Express populates it through middleware such as express.json() or express.urlencoded().
Follow-up: What happens if no parser runs? req.body remains undefined rather than containing parsed data.
req.body?The parser must be registered before the route handler that reads req.body. For JSON requests, app.use(express.json()) is a typical choice; URL-encoded forms use express.urlencoded().
Follow-up: Why might parsing still not occur? The request Content-Type must match the parser's expected type.
req.body be validated?The body has a user-controlled shape, so all properties and values must be treated as untrusted. Validate expected fields and types before invoking methods or using the values.
Follow-up: What kind of failure can unchecked access cause? A missing field may make property access fail, or a supplied value may have an unexpected type.
reqexpress.json()express.urlencoded()req.paramsreq.query