tezvyn:

Parse JSON and URL-encoded bodies in Express

AI-drafted, machine-checkedSource: interviewbeginner
WHAT IT TESTS

knowledge of built-in body parsers.

OUTLINE

express.json() for JSON, express.urlencoded() for form data, both registered via app.use().

RED FLAG

reaching for the deprecated body-parser package or forgetting extended option.

WHAT THIS TESTS This checks that you understand how Express turns a raw request stream into a usable req.body, and that the parsers ship built in since Express 4.16.

A GOOD ANSWER COVERS Express exposes express.json() and express.urlencoded() as built-in middleware. express.json() reads requests with Content-Type application/json and parses the body into a JavaScript object on req.body. express.urlencoded() handles application/x-www-form-urlencoded data from HTML forms. You apply them globally by calling app.use(express.json()) and app.use(express.urlencoded({ extended: true })) near the top of your app, before any route handlers, so every incoming request passes through them. Order matters: parsers must run before routes that read req.body.

COMMON WRONG ANSWERS Reaching for the standalone body-parser npm package; it still works but is redundant now that the functions are built into Express. Forgetting the extended option on urlencoded, which changes whether nested objects and arrays are supported (true uses the qs library, false uses Node's querystring). Registering the middleware after the routes, which leaves req.body undefined.

LIKELY FOLLOW-UPS What does the extended flag actually change? How do you limit body size to prevent abuse (the limit option)? How would you parse multipart form data for file uploads (you need multer, not these parsers)?

ONE CONCRETE EXAMPLE const express = require('express'); const app = express(); app.use(express.json()); app.use(express.urlencoded({ extended: true })); app.post('/users', (req, res) => res.json(req.body)); Now a POST with a JSON body lands fully parsed on req.body, and the same handler works for form submissions. Adding express.json({ limit: '1mb' }) caps payload size and protects against memory exhaustion from oversized requests.

Read the original → expressjs.com

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.