March 6, 2022

Node.js – HTTP Module

I think one of the most important modules in Node.js is the http module. This is because it helps you to create both server and client. Then you can transfer data over http(HyperText Transfer Protocol). Essentially, you can with the help of the http module, build a complete client-server web application.

Lets see how it works. We would consider the following 5 areas:

  1. How Web Servers Work
  2. The Architecture of a Web Application
  3. Creating a Web Server in Node.js
  4. Making a Request to the Server
  5. Creating a Web Client in Node.js

 

1. How Web Servers Work

A web server is simply a application that handles http requests. This requests come from http client. Http client is another application used to sent requests to the web server. For example, your browser. When a web server receives a http request, then it processes the request and send a http response back to the client. This response is normally a html(web) page. It may also include images, style sheets and scripts.

A web server could process a request either using server side scripting or by an application server.

 

2. The Architecture of a Web Application

A complete web application is normally made up of four layers.

  • The Client − This layer consists of internet browsers, or any other applications which can be used to  make HTTP requests to the server.
  • Server − This layer contains the Web server which can receive the requests made by the clients and pass them the response.
  • Business Service − This layer contains the application server which is used by the web server to process the request. This layer communicates with the data layer through a database driver or some other programs.
  • Data Store − This layer contains the database or any other source of data used by the web application. For example, MySQL database or MSSQL database.

The architecture of a web application is given below:

Web Application Architecture
Figure 1: Web Application Architecture

 

3. Creating a Web Server in Node.js

You can create a server in Node.js using the createServer method provided by the http module.

Let’s create  a web server that listens at port 8080. The code is given below:

var http = require("http");
var fs = require("fs");
var url = require("url");

//Create a http server
http.createServer(function(request, response){
    //extrate the urlpath from the request
    var urlpathname = url.parse(request.url).pathname;

    //Display the file name coming from th request
    console.log("Request from " + urlpathname);

    //Read the content of the file from the file system
    fs.readFile(urlpathname.substr(1), function(err, data){
        if(err){
            console.log("Error occured: " + err);

            
            //Write the http status to the response header
            response.writeHead(404, {"Content-type": "text/html"});
        }
        else {
            response.writeHead(200, {"Content-type": "text/html"})

            //Write the file content to the response body
            response.write(data.toString());
        }
        //send the response body to the client
        response.end();
    });
}).listen(8080);

// Write the message to the console
console.log("Server is running at port http://localhost:8080")

 

Next, we would create  a simple html page. This page would be placed in the same directory as the server. The content of the page is given below

<html>
   <head>
      <title>Servers in Node.js</title>
   </head>
   
   <body>
      It works!
	  The server is runing fine!
   </body>
</html>

 

4. Making a Request to the Server

Now run the program using the command node httpmodule.js

You will see that the server starts up. So open your browser and visit http://localhost:8080/index.html. You will see the page we created as shown below.

If you also look at the console window in VS Code, you will get additional information as shown below

PS D:\Documents\NodeJSTutorials1> node httpmodule.js
Server is running at port http://localhost:8080
Request from /index.html

 

5. Creating a Web Client in Node.js

Similar to creating a server, we can also create a http client in Node.js. We can do this using the request() method provided by the http module.So let’s create a file called httpclient.js. The content is as given below:

// First import the http module
http = require("http");

// Set the options to be used by the http request
var options = {
    host: "localhost",
    port: "8080", 
    path: "/index.html"
};

//Create a callback function that would handle the response
var callback = function(response) {
    var responseBody = "";
    response.on("data", function(data){
        responseBody = responseBody + data; //continuously update the response
    });
    response.on("end", function(){
        // All data received
        console.log(responseBody);
    });
}

//Now make the request to the server
var request = http.request(options, callback);
request.end();

 

Now, open another terminal and run this file (while the server is running). You will see that the body of the html page is displayed.

 

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments