Handling POST requests with Express and Node.js

HTML has featured forms for more than 20 years. Today, the form is still a powerful tool for building web applications. In web applications, users are often prompted to enter data into a form. To make use of that data, the web server must understand how to process it. Popular web server scripting languages include Java, ASP.NET, PHP, Python and Node.js. In this article, we will learn how to access the POST data sent to a Node.js web server.

To get started, clone the following git hub repository:

https://github.com/kevinchisholm/handling-POST-requests-with-express-and-node.js

(Instructions on how to run the code are available in the Git hub page.)

package.json

{
  "dependencies": {
    "body-parser": "^1.15.2",
    "express": "4.14.0"
  },
   "scripts": {
    "start": "node server.js"
  }
}

The package.json for this project is simple. We 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:

/require the express nodejs module
var express = require('express'),
    //set an instance of exress
    app = express(),
    //require the body-parser nodejs module
    bodyParser = require('body-parser'),
    //require the path nodejs module
    path = require("path");

In example # 1, we have imported the Node.js modules we need. The Express module takes care of the heavy lifting with regards to fulfilling web requests. If you are not familiar with the Express Node.js module, please see my earlier blog post on this subject:

http://www.nodejsconnect.com/blog/articles/getting-started-express-nodejs-web-application-framework

We also import the body-parser Node.js module. This module plays a critical role. It parses the body of an HTTP request. When it comes to processing a POST request, this is important. The path Node.js module helps express to construct a file path.

bodyParser.json and bodyParser.urlencoded

Example # 2:

//support parsing of application/json type post data
app.use(bodyParser.json());
 
//support parsing of application/x-www-form-urlencoded post data
app.use(bodyParser.urlencoded({ extended: true }));

In example # 2, we tell express to use the bodyParser.json middleware. This provides support for parsing of application/json type post data. We also tell express to use the bodyParser.urlencoded middleware. This provides support for parsing of application/x-www-form-urlencoded type post data.

Creating the node.js web server

Example # 3:

//tell express that www is the root of our public web folder
app.use(express.static(path.join(__dirname, 'www')));
 
//tell express what to do when the /about route is requested
app.post('/form', function(req, res){
    res.setHeader('Content-Type', 'application/json');
 
    //mimic a slow network connection
    setTimeout(function(){
 
        res.send(JSON.stringify({
            firstName: req.body.firstName || null,
            lastName: req.body.lastName || null
        }));
 
    }, 1000)
 
    //debugging output for the terminal
    console.log('you posted: First Name: ' + req.body.firstName + ', Last Name: ' + req.body.lastName);
});
 
//wait for a connection
app.listen(3000, function () {
  console.log('Server is running. Point your browser to: http://localhost:3000');
});

In example # 3, we use express.static to setup our static assets folder. The main purpose of this 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. This tells the Express module to wait for an HTTP request at the /form route, that leverages the POST HTTP verb. When the user sends a POST request to the /form route, Node.js executes the provided callback. The callback is the second argument passed to the app.post method.

The app.post callback takes two arguments. The first argument is the request object (i.e. "req"). The second argument is the result argument (i.e. "res"). We use the res.setHeader method to set the Content-Type header to application/json. This tells the users 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 this is to mimic a slow internet connection. Otherwise, the working example moves fast. For some, it might be difficult to understand what is happening.

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

Viewing the working code example

To see this code in action, you can make a POST request in your browser.

Follow these steps :

1) Clone the git hub repository. https://github.com/kevinchisholm/handling-POST-requests-with-express-and-node.js

2) Install the application: npm install

3) Start the application: npm start

4) Point your browser to: http://localhost:3000

5) In the web page, enter some text into the two input boxes, and then click the "Submit" button

6) Notice the logging statement in your node.js terminal

7) 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. You can 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.

Here is what happens when you submit the data in the browser :

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

(Nothing too fancy here, but the purpose of the example is to show 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. 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. While the working example is simple, it allows 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. Hopefully, this will get you started with your next form-based Node.js application!

Author

Kevin Chisholm

http://blog.kevinchisholm.com

Share This