Sunday, March 29, 2020

Node.js HTTP Module

Node.js HTTP Module

The HTTP Module in Node.js

Node.js offers http module to enable the applications with HTTP transmission, and it is one of the most important modules available in Node.js. This is a built-in module that allows Node.js applications to transfer data over the network using the HyperText Transfer Protocol (HTTP).

We can use the require() method to include this module,

var http = require('http');

Node.js as a Web Server

We can create an HTTP server that listens to server ports for any client requests and send a response back to the client. Node.js provides http module with a createServer method. This method returns an object that we can use to respond to HTTP requests over the network. This object inherits the http.Server prototype.

The Architecture of a web application

The architecture of typical web application can have client, web server, business service layer and data layer as its components,

Web Application architecture
Web Application architecture

Adding HTTP Header

We can create a web server in Node.js with HTTP Module, for this we can use createServer() method. We can add the HTTP header with content-type information in this method.

const http = require('http');
        http.createServer(function (request, response) {
          response.writeHead(200, {'Content-Type''text/html'});
          response.write("<h3>Welcome to the response page...</h3>");

        console.log('Server running at');

The first argument of the response.writeHead() method represents the status code, 200 means that, the response status is OK, and a second argument is an object providing HTTP content-type information to the response headers.

Read the Query(Request) String

The http.createServer() function has first argument as request argument. This argument contains the request object from the client (http.IncomingMessage object). This object holds url property received from the client appended to the domain name.

 const http = require('http');
        http.createServer(function (request, response) {
          response.writeHead(200, {'Content-Type': 'text/html'});
          response.write("URL: "+request.url);//url
console.log('Server running at');

Enter the http://localhost:3000/HomePage in your browser, you can see,

URL: /HomePage

as a result,

Parsing the Query String

We can parse the request string and retrieve the request parameters easily, for example

        const http = require('http');
        const url = require('url');

        http.createServer(function (req, res) {
          res.writeHead(200, {'Content-Type': 'text/html'});
          const q = url.parse(req.url, true).query;
          const txt = parseInt(q.num1) + parseInt(q.num2);
          res.end("sum is "+txt);


Enter the http://localhost:3000/?num1=100&num2=50 in your browser, you can see,

sum is 150

as a result