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:
const axios = require('axios');
axios.post('/todos', {
todo: 'Buy the milk',
});
The corresponding server-side code would look like this:
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);
});
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:
const server = http.createServer((req, res) => {
req.on('data', (chunk) => {
console.log(`Data chunk available: ${chunk}`);
});
req.on('end', () => {
// End of data
});
});
To access the data, assuming it is expected to be a string, you need to store it in 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'
});
});
Tags: Node.js, HTTP request, request body, JSON, Express, vanilla Node, body-parser