Express.js: Accessing request body

Introduction

In this tutorial we will learn how to obtain the parsed body of a request, using express.js, running on Node.js. For an introductory tutorial on this framework, please check here.

When setting up a HTTP web server, one common need is to be able to receive data sent by the server clients. Being this a standard functionality, express.js offers us a very easy way to obtain the parsed body of a request using middleware. You can check here a detailed explanation on how to use middleware with express, both built-in or from third parties.

In our case, we will be using built in middleware to handle two different content-type bodies: JSON and URL encoded. Note however that express.js has support for other data types that we are not going to cover on this tutorial (ex: text).

It is also important to mention that the middleware that we are going to use is only available in Express v4.16.0 onwards [1][2]. In my case I’m running version 4.17.1.

JSON body

Our first example will cover how to setup the server with a route listening to HTTP POST requests and then access the parsed JSON body from a request sent by a client.

We will begin our code by importing the express.js module, which exports the express function.

const express = require('express');

After importing the module, we will take care of creating an Application object. We do this by calling the express function mentioned above.

const application = express();

Now we will mount the middleware needed to parse the body of the request. We do this with a call to the use method on our Application object.

We will use the built in JSON middleware. This middleware is based on the body-parser [1] which, in versions of express.js previous to v4.16.0, needed to be explicitly installed.

For a list of supported optional options, please check here. For this example we won’t use any of the options, which means we are going with the defaults.

If the parsing of the body to JSON is successful, it will be available in the body property of the request object that is passed as input of the route handling function [1]. In case there is no body to parse, the Content-Type header doesn’t match “application/json” or an error occurred, an empty object will be obtained when accessing the body property [1].

application.use(express.json());  

After this we will declare a testing route, where we will accept POST requests, like mentioned before. We will use the index route, which corresponds to “/”. Recall from the previous tutorial that we register a route that listens to HTTP POST requests by calling the post method on our application object.

As first input we pass a string with the route and as second input a callback function that will be executed when a request is received on that route. When invoked by the express.js framework, the route handling function will receive two parameters:

  • Request object, which represents the HTTP request and contains properties of the request (including our parsed body).
  • Response object that represents the HTTP response from the Express.js application.
application.post('/', function(req, res){
   // Route handling function implementation
});

In the implementation of our handling function, we will access the body property of the Request object and print it to the console. Note that this will contain the data submitted by the client, which means that in a real application scenario we need to take care of all the validations, to make sure the data follows any rules we might have in our application.

In our case, the body property will contain an object that corresponds to the parsed JSON submitted by the client. This avoids us to have to parse it explicitly.

console.log(req.body);

To finish the handling of the request without sending any data, we call the end method on the Response object.

res.end();

The whole route declaration can be seen below.

application.post('/', function(req, res){
  
  console.log(req.body);

  res.end();
});

To finish our code, we need to call the listen method on our Application object, so it starts listening to incoming client requests. As first input, this method receives the port where the server will be listening and, as second input, a callback function that will be invoked after the app initialization is completed.

application.listen(8080, function(){
  console.log("Application initialized.");
});

The complete code can be seen below.

const express = require('express');

const application = express();
application.use(express.json());  

application.post('/', function(req, res){
  
  console.log(req.body);

  res.end();
});

application.listen(8080, function(){
  console.log("Application initialized.");
});

To test the code, first run it in a tool of your choice. I’ll be using Visual Studio Code with the Code Runner extension. As soon as the server is ready, you can send a POST request using a tool such as Postman (the one I’ll be using). Figure 1 illustrates sending a HTTP POST request with a testing JSON body, from Postman.

Sending HTTP POST request with JSON body.
Figure 1 – Sending HTTP POST request with JSON body.

After that, if you check the console where the server is running, you should see a result similar to figure 2. As can be seen, the route handling function was able to access the parsed JSON body and print it.

Printing the received JSON body from the express.js application.
Figure 2 – Printing the received parsed JSON body.

URL encoded body

Besides JSON, express.js also supports URL encoded body parsing [2] through this built in middleware. It behaves pretty much like we have described for the JSON use case: we mount the middleware and then, when it is able to parse the body content sent by the client, it becomes available in the body property of the Request object [2].

So, the testing code from this section will be pretty much similar to what we have seen before, except for the line where we mount the middleware.

Note that although the options object that can be passed to the middleware is optional, for this particular middleware we will get a deprecation warning in case we don’t provided the “extended” option, like shown below at figure 3. So, we will set this option to true, which means the qs library will be used to parse the URL encoded data.

Express.js url encoded middleware deprecation warning.
Figure 3 – Deprecation warning.

The code to mount the middleware can be seen below.

application.use(express.urlencoded({extended:true}));

We can check the whole code below. Like already mentioned, it is equal to what we had previously written except for the mounting of the middleware.

const express = require('express');

const application = express();
application.use(express.urlencoded({extended:true}))  

application.post('/', function(req, res){
  
  console.log(req.body);

  res.end();
});

application.listen(8080, function(){
  console.log("Application initialized.");
});

To test the code, like done in the previous section, use a tool such as Postman to submit a request, this time with a URL encoded body, like shown in figure 3.

Submitting HTTP POST request with URL encoded body, from Postman.
Figure 4 – Submitting HTTP POST request with URL encoded body, from Postman.

If you go back to the console where the server is running, you should see the object representing the parsed body, like shown in figure 5.

Printing the received parsed URL encoded body.
Figure 5 – Printing the received parsed URL encoded body.

References

[1] https://expressjs.com/en/4x/api.html#express.json

[2] https://expressjs.com/en/4x/api.html#express.urlencoded

Leave a Reply

%d bloggers like this: