Node JS Http Server Get Post Example

Node JS http module can be used to implement an http web server waiting for a client to request, it can also create an http client object which can send requests to another http webserver with query string or post data. This article will show you how to implement an http web server, how to send data to the webserver, and how to process get or post requests in the webserver with the node js application.

1. Node JS url, querystring, and http Module Overview.

  1. There are three built-in modules related to node js http server implementation.
  2. The url module is aimed to parse request URL.
  3. The querystring module is used to parse request query string or post data.
  4. The http module is used to create an http web server or http request client object.

1.1 Node JS http Module Example.

  1. Below is the example source code that implements the HTTP web server using the Node JS http module.
    // Include http module.
    var http = require('http');
    
    // Create http server.
    var httpServer = http.createServer(function (req, resp) {
    
        resp.writeHeader(200);
    
        resp.end('This is a node js created http web server. ');
    });
    
    // Http server listen on port 8888.
    httpServer.listen(8888);
    
    console.log("Http web server listening on port 8888. Access it with url http://localhost:8888.");
  2. When you browse a URL http://localhost:8888 in a web browser you can get the web page with the text This is a node js created http web server. on it.

1.2 Node JS url Module Example.

  1. Below is the Node JS url module example source code.
    // Include url module.
    var url = require('url');
    
    var urlString = 'https://cn.bing.com/search?q=java&first=11';
    
    var urlObject = url.parse(urlString, true, false);
    
    var hostName = urlObject.hostname;
    console.log("Host Name : " + hostName);
    
    var path = urlObject.path;
    console.log("Path : " + path);
    
    // Query string is a JSON object.
    var queryStringObject = urlObject.query;
    console.log("Query String : " + JSON.stringify(queryStringObject));
    
    // Create a new url based on the original url.
    var newUrlString = url.resolve(urlString, '/display?row=1');
    console.log('New Url String : ' + newUrlString);
  2. Below is the above code output.
    Host Name : cn.bing.com
    Path : /search?q=java&first=11
    Query String : {"q":"java","first":"11"}
    New Url String : https://cn.bing.com/display?row=1

1.3 Node JS querystring Module Example.

  1. Below is the Node JS querystring module example source code.
    // Include querystring module.
    var qString = require('querystring');
    
    var queryString = 'q=js&q=node&first=1';
    
    var queryStringObject = qString.parse(queryString);
    console.log("Query String : " + JSON.stringify(queryStringObject));
  2. Below is the above example output.
    Query String : {"q":["js","node"],"first":"1"}

2. Node JS Http Get Method Example.

  1. This example will create an http webserver which listens to client request and return request file content to the client.
  2. http_get_server.js
    // Include http ,fs and url module.
    var http = require('http');
    var fs = require('fs');
    var url = require('url');
    
    // Create http server.
    var httpServer = http.createServer(function (req, resp) {
    
        // Get an parse client request url.
        var reqUrlString = req.url;
        var urlObject = url.parse(reqUrlString, true, false);
    
        // Get user request file name.
        var fileName = urlObject.pathname;
        fileName = fileName.substr(1);
    
        // Read the file content and return to client when read complete.
        fs.readFile(fileName, {encoding:'utf-8', flag:'r'}, function (error, data) {
            
            if(!error)
            {
                /* Set Access-Control-Allow-Origin http header will fix No 'Access-Control-Allow-Origin' header is present on the requested resource error
                   when use XMLHttpRequest object to get this server page via ajax method. */
                resp.writeHead(200, {'Access-Control-Allow-Origin':'*'});
                resp.end(data);
            }else
            {
                resp.writeHead(404, {'Access-Control-Allow-Origin':'*'});
                resp.end(JSON.stringify(error));
            }
        });
    });
    
    // Http server listen on port 8888.
    httpServer.listen(8888);
    
    console.log("Access this example with url 'http://localhost:8888/http_get_server.js' to get js file source code.");
  3. When you open the URL http://localhost:8888/http_get_server.js in a web browser, it will display the http_get_server.js source code on the web page.
  4. You can also request the above http web server by executing the following code use the http get method.
  5. http_get_client.js
    // Include http ,fs and url module.
    var http = require('http');
    
    var requestOptions = {
        hostname:'localhost',
        port:'8888',
        method:'get',
        path:'/http_get_static_file_server.js'
    };
    
    // Create a http.ClientRequest object
    var request = http.request(requestOptions, function (resp) {
    
        var returnData = '';
    
        // When server return any data.
        resp.on('data', function (data) {
            returnData += data;
        })
    
        // When server return data complete.
        resp.on('end', function () {
            console.log(returnData);
        })
    
    });
    
    // Finish sending the request. Then serve will process this request.
    request.end();

3. Node JS Http Post Method Example.

  1. This example will send username and password in post method to an http web server, the webserver will then parse out client request action and extract post data and then process.
  2. http_post_server.js
    // Include http ,url module.
    var http = require('http');
    var url = require('url');
    
    // Create http server.
    var httpServer = http.createServer(function (req, resp) {
    
        // Get client request url.
        var reqUrlString = req.url;
    
        // Get client request path name.
        var pathName = url.parse(reqUrlString, true, false).pathname;
    
        // If request login action.
        if('/login' == pathName)
        {
            // Get request method.
            var method = req.method;
    
            // If post.
            if("POST" == method)
            {
                var postData = '';
    
                // Get all post data when receive data event.
                req.on('data', function (chunk) {
    
                    postData += chunk;
    
                });
    
                // When all request post data has been received.
                req.on('end', function () {
    
                    console.log("Client post data : " + postData);
    
                    // Parse the post data and get client sent username and password.
                    var postDataObject = JSON.parse(postData);
    
                    var userName = postDataObject.user_name;
    
                    var password = postDataObject.password;
    
                    /* Set Access-Control-Allow-Origin http header will fix No 'Access-Control-Allow-Origin' header is present on the requested resource error
                       when use XMLHttpRequest object to get this server page via ajax method. */
                    resp.writeHead(200, {'Access-Control-Allow-Origin':'*'});
    
                    if('jerry' == userName && '666666' == password)
                    {
                        resp.end('User name and password is correct. ');
                    }else
                    {
                        resp.end('User name and password is not correct. ');
                    }
                })
            }
        }
    });
    
    // Http server listen on port 8888.
    httpServer.listen(8888);
    
    console.log("Server is started.");
  3. http_post_client.js
    // Include http ,fs and url module.
    var http = require('http');
    
    var requestOptions = {
        hostname:'localhost',
        port:'8888',
        method:'POST',
        path:'/login'
    };
    
    // Create a http.ClientRequest object
    var request = http.request(requestOptions, function (resp) {
    
        var returnData = '';
    
        // When server return any data.
        resp.on('data', function (data) {
            returnData += data;
        })
    
        // When server return data complete.
        resp.on('end', function () {
            console.log(returnData);
        })
    
    });
    
    var postDataObject = {user_name:'jerry1', password:'666666'};
    
    // Write post data to server.
    request.write(JSON.stringify(postDataObject));
    
    // Finish sending the request. Then serve will process this request.
    request.end();

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.