Servers and environment

Get HTTP request body data using Node

Get the JSON sent in an HTTP request body in Node.js, with express.json() in Express or with the raw request stream data and end events.

Here is how you can extract the data that was sent as JSON in the request body.

If you are using Express, that is quite simple: the JSON parser is built in. Since Express 4.16 you call express.json() and no separate body-parser package is needed.

For example, to get the body of this request:

const axios = require('axios')

axios.post('/todos', {
  todo: 'Buy the milk',
})

This is the matching server-side code:

const express = require('express')
const app = express()

app.use(express.json())
app.use(express.urlencoded({ extended: true }))

app.post('/todos', (req, res) => {
  console.log(req.body.todo)
  res.sendStatus(204)
})

app.listen(3000)

When the client sends { todo: 'Buy the milk' }, the server logs Buy the milk.

If you are not using Express and you want to do this in vanilla Node, you need to do a bit more work, of course, as Express abstracts a lot of this for you.

The key thing to understand is that when you initialize the HTTP server using http.createServer(), the callback is called when the server got all the HTTP headers, but not the request body.

The request object passed in the connection callback is a stream.

So, we must listen for the body content to be processed, and it is processed in chunks.

We first get the data by listening to the stream data events, and when the data ends, the stream end event is called, once:

const server = http.createServer((req, res) => {
  // we can access HTTP headers
  req.on('data', (chunk) => {
    console.log(`Data chunk available: ${chunk}`)
  })
  req.on('end', () => {
    //end of data
  })
})

So to access the data, assuming we expect to receive a string, we must put it into an array:

const server = http.createServer((req, res) => {
  let data = []
  req.on('data', (chunk) => {
    data.push(chunk)
  })
  req.on('end', () => {
    const body = JSON.parse(Buffer.concat(data).toString())
    console.log(body.todo) // 'Buy the milk'
  })
})

If the client sends invalid JSON, JSON.parse throws. Wrap it in try/catch and return 400 Bad Request instead of crashing the server.

Try this on your own project: send a POST with curl and confirm the parsed field matches what you sent. A missing Content-Type: application/json header is a common reason the body looks empty on the server side.

Lesson completed