Use Node to get HTTP request body data

Learn how to use Node to extract data sent in JSON format via HTTP request body

This is how you can extract the data sent as the followingJSON formatIn the request body.

If you’re using Express, it’s easy: usebody-parserNode 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 don't use Express, and you want to perform this operation in normal Node, then of course you need to do more work, because Express abstracts a lot of this kind of content for you.

The key to understand is when you initialize the HTTP server with the following commandhttp.createServer(), The callback will be called when the server gets all the HTTP headers instead of the request body.

ThisrequestThe object passed in the connection callback isstream.

Therefore, we must listen to the main content to be processed, and the main content is processed in blocks.

We first get the data by listening to the streamdataEvent, when the data ends, the flowendOne call event:

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

Therefore, to access the data, suppose we want 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', () => {
    JSON.parse(data).todo // 'Buy the milk'
  })
})

Download mine for freeNode.js manual


More node tutorials: