DEV Community

flavio ⚡️🔥
flavio ⚡️🔥

Posted on • Originally published at flaviocopes.com on

6 2

Get HTTP request body data using Node

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('https://flaviocopes.com/todos', {
  todo: 'Buy the milk'
})
Enter fullscreen mode Exit fullscreen mode

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(request.body.todo)
})
Enter fullscreen mode Exit fullscreen mode

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 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
  })
})
Enter fullscreen mode Exit fullscreen mode

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', () => {
    JSON.parse(data).todo // 'Buy the milk'
  })
})
Enter fullscreen mode Exit fullscreen mode

Tiugo image

Modular, Fast, and Built for Developers

CKEditor 5 gives you full control over your editing experience. A modular architecture means you get high performance, fewer re-renders and a setup that scales with your needs.

Start now

Top comments (2)

Collapse
 
rxbsxn profile image
Robert Harężlak

This fragment of code will not work, because you are using undefined variable

app.post('/endpoint', (req, res) => {
  console.log(request.body.todo) // Replace request -> req
})
Collapse
 
flaviocopes profile image
flavio ⚡️🔥

Good catch, thanks!

👋 Kindness is contagious

Dive into this thoughtful article, cherished within the supportive DEV Community. Coders of every background are encouraged to share and grow our collective expertise.

A genuine "thank you" can brighten someone’s day—drop your appreciation in the comments below!

On DEV, sharing knowledge smooths our journey and strengthens our community bonds. Found value here? A quick thank you to the author makes a big difference.

Okay