AI Workshop: learn to build apps with AI →
HTTP and Networking: Get HTTP request body data using Node

Join the AI Workshop and learn to build real-world apps with AI. A hands-on, practical program to level up your skills.


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

If you are using Express, that’s quite simple: use the body-parser Node module.

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 bodyParser = require('body-parser')

app.use(
  bodyParser.urlencoded({
    extended: true,
  })
)

app.use(bodyParser.json())

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

If you’re 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’s processed in chunks.

We first get the data by listening to the stream data events, and when all data has been received, the stream’s end event fires 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, we collect the chunks in an array and then concatenate them before parsing (since the body may arrive in multiple chunks):

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'
  })
})

Lessons in this unit:

0: Introduction
1: Run a web server from any folder
2: HTTP requests in Node using Axios
3: Make an HTTP POST request using Node
4: Making HTTP requests with Node
5: ▶︎ Get HTTP request body data using Node
6: Serve an HTML page using Node.js
7: Using WebSockets with Node.js