Node.js LogoLearn how to access the body of an HTTP POST request using the Express.js framework and body-parser module.

Forms are a common component in web applications. When a user submits a form, that data is sent to the back-end for processing. To process that data, the web server must understand how to access it. Popular web server languages include Java, .NET, PHP, Python and Node.js. In this article, we’ll learn how to access the POST data sent to a Node.js web server using the Express.js framework. To get started, you can go ahead and clone the following github repository: Handling POST requests with Express and Node.js.

And you’ll find instructions on how to run the code in the Github page.

package.json

The package.json for this project is pretty straightforward, and we’ll only need the body-parser and express Node.js modules. We also create a scripts property so that running the example code requires a simple command: npm start.

Requiring the modules we need – Example # 1:

In Example # 1, we’ve imported the Node.js modules that we need. The Express module takes care of the heavy lifting with regard to fulfilling web requests. NOTE: If you’re not familiar with the Express Node.js module, please see my earlier blog post on this subject:  Set up a Node / Express Static Web Server in Five Minutes.

We also import the body-parser Node.js module, which has the critical role of parsing the body of an HTTP request. When it comes to processing a POST request, this is important. And the path Node.js module helps express to construct a file path.

bodyParser.json and bodyParser.urlencoded – Example # 2:

Now, here in Example # 2, we tell express to use the bodyParser.json middleware, which provides support for parsing of application/json type post data. We also tell express to use the bodyParser.urlencoded middleware, which provides support for the parsing of application/x-www-form-urlencoded type post data.

Creating the node.js web server – Example # 3:

In Example # 3, we use express.static to set up the static assets folder, the main purpose of which is to help the working example function in a browser, with minimal effort. For more information on express.static, please see my earlier blog post in Express mentioned above. In this example, we use the app.post method, which tells the Express module to wait for an HTTP request at the /form route that leverages the POST HTTP verb. So, when the user sends a POST request to the /form route, Node.js executes the provided callback, which is the second argument passed to the app.post method.

The app.post callback takes two arguments, the first of which is the request object (i.e. “req”). The second is the result argument (i.e. “res”). We use the res.setHeader method to set the Content-Type header to application/json, which tells the user’s browser how to properly handle the returned data from the request.

NOTE: We wrap the rest of the callback code in a setTimeout, the purpose of which is to mimic a slow internet connection. Otherwise, the working example will move too fast for most to comfortably follow.

Inside the setTimeout, we use the res.send method to send the result body back to the user, and here we’re sending a serialized JSON object. To construct this object, we access the body property of the req object (i.e. the request object), which is why we have implemented the bodyParser.json middleware. And this is what allows us to parse the properties of the request body. In this example, we are expecting firstName and lastName POST parameters, which will allow us to access the req.body.firstName and req.body.lastName properties, to build the JSON for our result object.

To see this code in action, just follow these steps :

  1. Clone the git hub repository: https://github.com/kevinchisholm/video-code-examples/tree/master/node-express/handling-POST-requests-with-express
  2. Follow the instructions in the readme to set up the code
  3. Point your browser to: http://localhost:3000
  4. In the web page, enter some text into the two input boxes, and then click the “Submit” button
  5. Notice the logging statement in your node.js terminal
  6. Notice that the text you entered displayed in a browser message

You might also want to take a look at the Network tab in your Web Developer Tools, which allows you to see the actual network request that goes to the web server. You’ll be able to inspect the POST data sent, and the JSON data returned.

Viewing the working code example

Here’s what happens when you submit the data in the browser:

  1. The JavaScript in www/js/form-handler.js makes an AJAX POST call to the route: /form.
  2. The object sent in the POST request is: {firstName: XXX. lastName: XXX}. (NOTE: “XXX” is whatever value entered into the form’s text inputs.)
  3. Our Node.js web server intercepts the HTTP request to /form.
  4. Our Node.js web server parses the body of the HTTP request and constructs a JSON object.
  5. The XMLHttpRequest for the AJAX call is this JSON object.
  6. The browser displays the data from this JSON object in the browser.

Nothing too fancy here, just illustrating the “round trip” of our HTTP POST request.

Summary

In this article, we learned how to handle POST requests with the Express node.js module, and we talked about the need for bodyParser.json and bodyParser.urlencoded. We also learned how to listen for a POST request to a specific route, and how to access the POST parameters in the HTTP request body. Now, while the working example is simple, it does allow you to inspect every step of the process. If you look at your browser’s network tab, you can see the HTTP POST request go out, and then return. What happens during the server-side processing of that request is what you see in our Node.js code: server.js.

So, a lot to digest at first, but I’m hoping that this it will get you started with your next form-based Node.js application!