top of page

How to read the body of a HTTP(S) POST request in node.js

Updated: Sep 18, 2021

Many of us working with node.js already know the answer but I would like to write this post for the newcomers. In cloud native development we often develop micro services using node.js because it's obvious advantages. In this post I will describe how we can read the body of a post request with very little code.

 

Contents

 

What is the Server of choice in node.js?

We first need to know how we create an application server in node.js. Though there are many articles available on the web I would like to briefly show how we can run an application server. We all use the express module in node.js to create a server that runs in a particular port and accepts all incoming requests. Here is an example of the same.

const app = require('express')();
const port = 5000;

app.get('/', (request, response) => {
  response.send('Hello World!');
})

app.listen(port, () => {
  console.log(`My app listening at http://localhost:${port}`);
})

Using the above code we will be able to spin up an application server that accepts a HTTP GET request. The root path http://localhost:3000/ will return 'Hello World!' as a string in response. Now the question is how we can serve HTTP POST requests ? we can add this route show below

app.post('/', function(request, response) {
  let body = request.body;
});

By adding these lines before the app.listen() statement, our application server will start accepting a POST request in root path http://localhost:3000/ . We expect that we just can read the request body and put it in the body variable. But the line let body = request.body written inside does not work as we expect.


Why is the request body not present in the request variable?

You know that Express and node.js is asynchronous and works with events. You also need to know that data in NodeJs with Express is streamed. Means data comes in a chunk of packages. See the post How to access response data without body-parser to know how data from the request body is collected. The whole request data is not available when the POST request is received and hence we don't get the request body by default. For most of the cases the body-parser (https://www.npmjs.com/package/body-parser) comes in rescue.


What is body-parser?

The body-parser is a module in node.js that provides us the request body as we would like to access in our code. It works as middleware and parses the incoming request bodies before the request handlers that we have written (app.get(), app.post() etc.) are hit. The body-parser makes the request body available in request.body property. It's important that we "use" the body parser before the request handlers we have written.


What kind of requests body-parser can parse?

I wrote body-parser can work for most of the cases. As you know data can be sent in different formats in HTTP request and response. We can specify in the Content-Type header what is the type of data the request or response contains. For example

application/x-www-form-urlencoded
multipart/form-data
application/json
application/xml

Body-parser can only parse

Json data

Raw data

Text data

URL-encoded data


How to use body-parser in node.js ?

Express has the use() function that allows us to apply any code for all requests coming to our application. This use() method allows us to plugin any middleware function that we would like to execute before our requests handlers with different routes are reached. For example,

app.use(function(request, response) {
  console.log("I am a middleware")
});

app.get('/', function(request, response) {
  response.send('Hello World!');
});

The console.log statement will print every time a get request (or any request for which we have a handler) is received before the app.get() handler returns a response. This happens because the function supplied in app.use() executes before the supplied function in app.get() is reached.


We can use the app.use() function and supply body-purser methods that can handle all incoming requests and makes the POST or PATCH request body available in request.body parameter. We just need to add one line before our request handlers

app.use(bodyParser());

To parse json data in request body and URL encoded data in request URL we need the specific methods in body parse that does the job

const express = require('express');
const app = express();
const port = 5000;

app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded

app.get('/', (request, response) => {
  response.send('Hello World!');
})
app.post('/', function(request, response) {
  let body = request.body;
});


app.listen(port, () => {
  console.log(`My app listening at http://localhost:${port}`);
})

There are several parameters that can be specified while initializing the body-parser, for example

app.use(bodyParser.json({limit: '10kb'}));
app.use(bodyParser.urlencoded({limit: '10kb',extended: true}));

In the above two methods we have mentioned that the maximum size of the request body can be 10kb. Body-parser allows us to specify several parameters as options. See the body-parser documentation here https://www.npmjs.com/package/body-parser.


How to use body-parse in a specific route?

This code snippet shows how we can create different types of body parsers and can apply them in different routes in the application server. This code snippet shows how we can create different types of body parsers and can apply them in different routes in the application server.

const express = require('express');
const bodyParser = require('body-parser'); 
const app = express();
const jsonParser = bodyParser.json(); 
const urlencodedParser = bodyParser.urlencoded({ extended: false })
 
app.post('/login', urlencodedParser, function (req, res) {
  res.send('welcome, ' + req.body.username);
})
 
app.post('/api/users', jsonParser, function (req, res) {
 let body = req.body;
…
})

In this post we have learned how body-parse node module can help parsing HTTP requests bodies in a micro service written in node.js







1,308 views0 comments

Recent Posts

See All
bottom of page