Node JS Http Server Get Post Example

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

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

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

1.1 Node JS http Module Example.

// 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.");

node js http web server example

1.2 Node JS url Module Example.

// 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);

Below is 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.

// 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));

Below is the output.

Query String : {"q":["js","node"],"first":"1"}

2. Node JS Http Get Method Example.

This example will create a http web server which listen to client request and return request file content to client.

READ :   Use Node.js To Create Http Web Server And Process Web Page Example

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.");

node js http web server return file content

You can also request above http web server by execute following code use http get method.

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.

This example will send username and password in post method to a http web server, the web server will then parse out client request action and extract post data and then process.

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.");

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();
(Visited 801 times, 5 visits today)

Leave a Reply

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.