Node.js HTTP Client

In the last article we studied how we can create a web server via node.js which listens to HTTP requests and sends back HTTP response. We created a simple “main.htm” file and placed it in the root directory of the code file for server. We then used our browser to access that file. Here browser worked as HTTP client. However, as we wrote node.js HTTP web server, we can also write node.js HTTP client

Before we execute the code for node.js HTTP client and test its ability to access the file “main.htm” on the server, you must have your server running and you should also have “main.htm” file placed in the root directory if the code file for the server. If you do not know how to set up an HTTP server and how to create and place file “main.htm”, go back to the previous article and do that. Then come back and follow the article from here.

Creating a Node.js HTTP Client

The following code creates an HTTP client that requests for file “main.htm” from the server “localhost” running at port 9006. Take a look at this code.

var http = require('http');

// Options to be used by request 
var reqparams = {
   host: '127.0.0.1',
   port: '9006',
   path: '/main.htm'  
};

var readResponse = function(response){

   var page = '';
   response.on('data', function(data) {
      page += data;
   });
   
   response.on('end', function() {
      console.log(page);
   });
}

var request = http.request(reqparams, readResponse);
request.end();

Download the code Try the code

Take a look at the above code. Here first we import the http module via require. This returns an http instance. Next we specify the parameters for the request. It is basically an associative array. Here first item is the host address, the second item is the port and the third one is the name of the file you wish to retrieve from server. Next, we create a callback function “readResponse”. Finally we call request function on http instance. This function takes two parameters, the request parameters in the form of associative array and the call back function used to read the response which in our case is “readResponse”. So as soon as the client starts receiving response it is added to the page variable. Finally when all the response has been received, the page variable is displayed via console.log. This should contain the html content of main.htm you created in last article.

<<< Node.JS Web ServerNode.JS Express Framework >>>
Copyright 2005-2016 KnowledgeHills. Privacy Policy. Contact .