Request bodies
JSON
app.use(express.json())
app.post('/users', (req, res) => {
res.status(201).json(req.body)
})
Parses application/json into req.body. Without a parser, req.body stays undefined. See express.json().
Form bodies
app.use(express.urlencoded({ extended: true }))
Parses HTML form posts. extended: true allows nested fields; the default only handles flat keys. See express.urlencoded().
Size limit
app.use(express.json({ limit: '1mb' }))
Caps the request body. Larger payloads fail with a 413 that reaches your error handler. See express.json().
Missing body
app.post('/users', (req, res) => {
const name = req.body?.name
res.json({ name })
})
Guards against unparsed bodies. Optional chaining avoids a crash when the client sends no JSON. See req.body.
Related links
- express.json() reference (expressjs.com)
- express.urlencoded() reference (expressjs.com)
0 Comments for this cheatsheet. Write yours!