How to parse POST request in Node JS without using Express JS body-parser

How to parse POST request in Node JS without Express JS body parser

Hello Friends 🙏, This week I was playing with NodeJS and found an intresting topic, How to parse POST request in Node JS without ExpressJS body-parser.

You must have used ExpressJS body-parser to read the POST request data while creating API in Node JS, but do you know why we use it and how can we parse the POST request body in Express without body parser 😎.

I wrote this tutorial, while I was working on another related topic, you can check it out here: How to create API in NodeJS without Express JS 🤘

Chalo suru kiya jaye!🍻 Lets start! 🕺

What is the use of body-parser?

Basically, body-parser usage is related to ‘POST’ method. When we use POST method, we send some data with the API call.
Data can be sent in many formats like: form-data, x-www-form-urlencoded, raw, binary, GraphQL.

In this tutorial, We will post data in x-www-form-urlencoded format.

how to parse post request in node js,what is buffer in javascript,node parse post body,node js,node js tutorial

But at server, we cannot directly access the request data. Like if try to get body the request, it will be undefned.

http.createServer((request, response) => {
  const data = request.body;
  console.log("Data: ", data);
})

server.listen(9000, () => {
  console.log("Server is running on Port 9000");
});

This will give below result:

how to parse post request in node js,what is buffer in javascript,node parse post body,node js,node js tutorial

This is because http request object is a readable stream.

In a readable stream, data arrives in parts/chunks and there are some events that get emitted like at the start data event is emitted and when all parts/chunks have arrived, an end event is emitted.

So in ExpressJS we use body-parser, which helps to collect all the chunks received and then parse that chunk into an accessible data format.

How to parse POST request in Node JS

To parse the POST request body in Node JS without using Express JS body-parser, We have to listen events, emitted by the request, ie. ‘data’ event and ‘end’ event.
Below is the code to listen those events:

http.createServer((request, response) => {
  const chunks = [];
  request.on("data", (chunk) => {
    chunks.push(chunk);
  });
  request.on("end", () => {
    console.log("all parts/chunks have arrived");
    const data = Buffer.concat(chunks);
    console.log("Data: ", data);
  });
})

Above we are using Buffer.concat(), it is a method available in Node JS Buffer class, it join all the received chunks and returns a new Buffer.

Now if we again access the POST API from Postman, we will get below result:

how to parse post request in node js,what is buffer in javascript,node parse post body,node js,node js tutorial

This format of data is a buffer, Buffer is used to handle the binary streams of data.
We can convert it to string to get a readable format. Add below lines to convert:

const stringData = data.toString();
console.log("stringData: ", stringData);

Now we will get below result:

how to parse post request in node js,what is buffer in javascript,node parse post body,node js,node js tutorial

As you can see, we are now getting data in querystring format. But still, to make it accessible to code we have to convert it into an Object format.
To do this, we wil use Node JS URLSearchParams, its has utility methods to work with the query string, using this we will be converting querystring to URLSearchParams object instance and then using .entries() method, we can iterate through the params and can get the data in an Object format. Below is the code:

const parsedData = new URLSearchParams(stringData);
const dataObj = {};
for (var pair of parsedData.entries()) {
  dataObj[pair[0]] = pair[1];
}
console.log("DataObj: ", dataObj);

Check here the final server.js file.

Again on accessing the POST API from Postman, we will get below result:

how to parse post request in node js,what is buffer in javascript,node parse post body,node js,node js tutorial

Now we are getting data in Object format and it can be easily accessed in the code.

Checkout the project here.

Thats all in this Node JS tutorial, here we learned how to parse the POST request body in Node JS without using Express JS body-parser and also learned what is Buffer in JavaScript and how to convert Buffer data into readable and accessible data format.
This is just for understanding the logic behind the body-parser. For a serious application, you can use Raynos/body.

If you have any question or suggestion, please feel free to comment.

Thanks 🙏.

Leave a Comment

Your email address will not be published.