Get HTTP request body data using Node
By Flavio
Published · Updated
Tagged: Node.js
Read a JSON POST body in Node.js with express.json() or the built-in HTTP module. Handle malformed JSON, missing headers, and body size limits.
In Express, run express.json() before your route handler, then read the parsed object from req.body.
With Node’s built-in HTTP server, the body arrives in chunks that you collect and parse yourself.
Read a JSON body in Express
In an empty folder, run npm init -y and npm install express. Save this as server.cjs and run node server.cjs.
const express = require('express')
const app = express()
app.post('/todos', express.json({ limit: '16kb' }), (req, res) => {
if (typeof req.body?.todo !== 'string') {
return res.status(400).json({ error: 'Expected a todo string' })
}
res.json({ todo: req.body.todo })
})
app.listen(3000)
From another terminal, send the route some JSON.
curl -sS http://localhost:3000/todos \
-H 'Content-Type: application/json' \
--data '{"todo":"Buy the milk"}'
{"todo":"Buy the milk"}
If req.body is undefined in Express 5, check the request’s Content-Type and where you registered the parser.
Here it runs only for POST /todos. If several routes need the same parser, you can put app.use(express.json({ limit: '16kb' })) above those routes.
The parser gives you a JavaScript value. The typeof check still matters because the client can send JSON with a missing todo or a number where you expect a string.
Express responds with HTTP 400 for malformed JSON and HTTP 413 when the body exceeds the limit. Add -i to the curl command to see the status, and try sending {"todo":} to see the 400. Express documents the parser’s errors.
If your client sends a regular HTML form, use the parser for URL-encoded form fields. A multipart/form-data upload needs its own parser.
Read a JSON body with Node’s HTTP module
Node calls your handler after it reads the headers.
The request body is a readable stream. We collect the buffers and decode them together because a UTF-8 character can span two chunks.
Stop the Express server before running this version. Save it as server.cjs and run the same curl command.
const { createServer } = require('node:http')
createServer((req, res) => {
if (req.method !== 'POST' || req.url !== '/todos') {
res.writeHead(404).end()
return
}
const type = req.headers['content-type']?.split(';')[0].trim().toLowerCase()
if (type !== 'application/json') {
res.writeHead(415).end()
return
}
const chunks = []
let bytes = 0
req.on('error', () => res.destroy())
req.on('data', chunk => {
if (res.writableEnded) return
bytes += chunk.length
if (bytes > 16 * 1024) {
chunks.length = 0
res.writeHead(413).end()
return
}
chunks.push(chunk)
})
req.on('end', () => {
if (res.writableEnded) return
let body
try {
body = JSON.parse(Buffer.concat(chunks).toString('utf8'))
} catch {
res.writeHead(400).end('Invalid JSON')
return
}
if (typeof body?.todo !== 'string') {
res.writeHead(400).end('Expected a todo string')
return
}
res.writeHead(200, { 'Content-Type': 'application/json' })
res.end(JSON.stringify({ todo: body.todo }))
})
}).listen(3000)
Count the bytes you receive even if the request has no Content-Length header. Once we send 413, the data handler discards any remaining chunks and the end handler skips parsing.
Want me to talk about your product? You can sponsor this site.
Related posts about node: