req.body after a POST request with JSON {"name":"Alice","age":30}?import express from 'express'; const app = express(); app.use(express.json()); app.post('/user', (req, res) => { res.json(req.body); });
The express.json() middleware parses the incoming JSON string and converts it into a JavaScript object. So req.body will be the parsed object {name: 'Alice', age: 30}.
application/x-www-form-urlencoded. Which middleware usage is correct?import express from 'express'; const app = express(); // Middleware to parse form data here app.post('/submit', (req, res) => { res.json(req.body); });
The express.urlencoded() middleware parses URL-encoded form data. The extended: true option allows rich objects and arrays to be encoded.
req.body remain empty when sending JSON data?req.body empty after sending JSON data in a POST request?import express from 'express'; const app = express(); app.post('/data', (req, res) => { res.json(req.body); }); app.use(express.json());
Middleware in Express runs in the order it is declared. Since express.json() is declared after the route, the route handler runs before the body is parsed, so req.body is empty.
req.body after sending multipart/form-data without middleware?Content-Type: multipart/form-data but do not use any middleware to parse it. What will req.body contain?import express from 'express'; const app = express(); app.post('/upload', (req, res) => { res.json(req.body); });
Express does not parse multipart/form-data automatically. Without middleware like multer, req.body is undefined.
The correct setup is to use express.json() and express.urlencoded() with proper options. The order does not strictly matter, but both must be included. The extended option is required for express.urlencoded(). Option A uses valid syntax and options.