Extracting HTTP Request Body Data Using Node
Learn how to efficiently extract data sent as JSON through an HTTP request body using Node.
To extract the data from the request body when using Express, you can simply utilize the popular body-parser
Node module.
For instance, if you want to retrieve the body of a POST request:
1 | const axios = require('axios'); |
The corresponding server-side code would look like this:
1 | const bodyParser = require('body-parser'); |
However, if you’re not employing Express and prefer to perform this task using vanilla Node, it requires some additional work since Express conveniently abstracts many of these details for you.
Understanding that the http.createServer()
callback is called once the server receives all the HTTP headers but not the request body is crucial.
The request
object passed in the connection callback is a stream, specifically a readable stream.
Consequently, you must listen for the body content to be processed since it’s received in chunks.
To start, you can access the data by listening to the stream’s data
events, and when the data ends, the end
event is triggered:
1 | const server = http.createServer((req, res) => { |
To access the data, assuming it is expected to be a string, you need to store it in an array:
1 | const server = http.createServer((req, res) => { |
Tags: Node.js, HTTP request, request body, JSON, Express, vanilla Node, body-parser