DotNetCurry Logo

Process Data over HTTP in Node.js

Posted by: Mahesh Sabnis , on 12/2/2015, in Category Node.js
Views: 8679
Abstract: Using Node.js to process the data posted via a HTML page by the client. We will check the request method GET and POST and respond accordingly.

Node.js provides several built-in modules for various server side operations. For example, we can create web server in Node.js using http module, perform File IO operations using fs module and so on. When we create Web server using Node.js and manage requests processing through it, we can also store Html files on this server and deliver to a client’s http request. However what if the client wants to post some data via a html page and expects the Node.js web server to process it? Yes we can do this too by implementing the request method check e.g. GET, POST, etc.

 

In this article, we will implement Node.js application which will process the data posted by the client using the HTML page delivered to it.

This application is developed using Visual Studio Code. This is a new FREE cross-platform editor for building and debugging modern web and cloud applications. We also need Node.js tools so that we can install necessary Node modules. Please visit following links to grab related information about Visual Studio Code.

https://code.visualstudio.com/Docs/editor/codebasics

https://code.visualstudio.com/Docs/runtimes/nodejs

Download Node tools from the following link https://github.com/Microsoft/nodejstools#readmejs

Node.js Implementation

Step 1: Create a folder on your hard drive (say E:\) with the name VSCodeProcessPostedData. Under this folder, add a new folder of name Scripts. We will be using this subfolder to store our application files. Open Visual Studio Code. Open the VSCodeProcessPostedData folder using File > Open Folder Option. Once the folder is opened, the option for creating new file will be displayed as shown in the following image. Select the Script folder and click on the new file icon as shown in the following image. This will provide a blank textbox where you can create a new file and call it as appjs.

vscode-process-data

Step 2: In the VSCodeProcessPostedData folder, add a folder of name AppPages. In this folder add a new HTML file of name MyPage.html. Add the following markup in it:

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <title>The Page Returned by Making Http Call to Node.js</title>
    <style type="text/css"> 
        table, td {
          border:double;
        }
    </style>
</head>
<body>
    <h1>Product Information Page</h1>
    <form method="post">
        <table>
            <tr>
                <td>Product Id:</td>
                <td>
                    <input type="text" name="pid" id="pid"/>
                </td>
            </tr>
            <tr>
                <td>Product Name:</td>
                <td>
                    <input type="text" name="pname" id="pname"/>
                </td>
            </tr>
            <tr>
                <td></td>
                <td>
                    <input type="submit" value="Save" />
                </td>
            </tr>
        </table>
    </form>

</body>
</html>

This is a simple HTML file which will be sent to the client upon request.

Step 3: Open app.js and add the following code in it:

//1.
var http = require('http');
var fs = require('fs');

//2.
var productPage = fs.readFileSync('./AppPages/MyPage.html');

//3.
var server = http.createServer(function (req, resp) {
    //4.
    if (req.method === "GET") {
        resp.writeHead(200, { 'content-type': 'text/html' });
        resp.end(productPage);
    }
    //5.
    if (req.method === "POST") {
        var productData = '';
        //6.
        req.on('data', function (prd) {
            productData += prd;
        }).on('end', function () {
            console.log('The received data is ' + productData.toString());
            resp.end('Data received  from you is ' + productData.toString());
        });          
    }
});
server.listen(5050);
console.log('Server started on  5050');

The above code performs the following operations (Note: Comments on each line match with the numbers used in the following points):

1. Load the http and fs module. These modules will be used to create web server and for performing file operations.

2. Read the html file synchronously, so that after the completion of the read operation, the request processing can be started.

3. Create an http server for request processing.

4. Detect the request method, if it is GET then respond with the Html file for the request.

5. If the request is of the type POST, then read the posted data and process it. On the request end the data will be displayed on the console on the server side and will be responded back to the client’s request.

 

 

Step 4: Right-Click on app.js and select Open in Command Prompt option. This will show the command prompt from where we can run the application.

command-prompt

On this command prompt, enter the following command

Node app

The following result will be displayed:

node-started

Step 5: Open any browser and enter the following URL in the address bar

http://localhost:5050

The following result will be displayed:

product-info

Enter Product Id as 101 and Product Name as Laptop and click on the Save button, the following result will be displayed

nodejs-data-received

This shows the posted data sent back to the client. We can see the posted data on the server side as well, as shown in following image

data-posted

Conclusion

In Node.js using http module we can not only deliver a html response to the client, but also process the data posted by the client.

Download the entire source code of this article (Github)

Was this article worth reading? Share it with fellow developers too. Thanks!
Share on LinkedIn
Share on Google+
Further Reading - Articles You May Like!
Author
Mahesh Sabnis is a DotNetCurry author and Microsoft MVP having over 17 years of experience in IT education and development. He is a Microsoft Certified Trainer (MCT) since 2005 and has conducted various Corporate Training programs for .NET Technologies (all versions). Follow him on twitter @maheshdotnet


Page copy protected against web site content infringement 	by Copyscape




Feedback - Leave us some adulation, criticism and everything in between!