NodeJS - SPLessons
SPLessons 5 Steps, 3 Clicks
5 Steps - 3 Clicks

Node.js Http Module

Node.js Http Module

shape Introduction

The Node.js Http (Hypertext Transfer Protocol) Module contain few properties, event and functions which implement http clients and servers. Following are the concepts covered.
  • HTTP Overview
  • Node.js HTTP module functions
  • Reading POST request

HTTP Overview

shape Description

The HTTP stands for Hypertext Transfer Protocol and is the application protocol for the collaborative, distributed and hypermedia information system. The World Wide Web data communication system is based on HTTP, the network communication elements in http are of two types they are http client and http server. The HTTP request is processed through a web server and the fundamental network protocol is utilized to distribute data on the World Wide Web. The term can allude either to the whole system or particularly to the software which accepts and regulates the HTTP requests. The most widely recognized utilization of web servers is to host sites, yet there are different uses, for example, email handling, gaming, storage of data or other uses. The HTTP server get a request from the HTTP client, the client get response back from the server. Both the request and responds have two parts called header and body. Generally the header is sent before the body and these header contains the meta data or the information about the body of a message. Usually the body of a message have the image, css or other files.

Node.js HTTP module functions

shape Description

A browsed website on the browser is the combination of numerous requests and the corresponding responses. An html file is first requested by the browser, while parsing the arrived html file as response, it discovers other required files such as image files, JavaScript files.  At that point, the browsers sends the request for each of the required files and receive the comparing file as a response and this communication can be seen in any browsers, in order to see this open the developer tool or its substitutes and go to the network sections and open the network section of the web developer tools of any browser and look at the http action. In order to create the Node.js HTTP server there are various functions as follows. http.createServer([requestListener]) - The HTTP server can be created using this function and the server created do not accept any request but returns an object of the http.server class. The fucntion accepts only on e argument which listens the event request  included with request and responds parameters which are supplied by Node.js The request object is used to get the current http request information and the responds object is used to send for the current http request. server.listen([port][, hostname][, backlog][, callback]) - The function accepts the request by listening to the given port and host by client, the function have four arguments as follows. When the post and hostname not given the function listens to the path given and is known as the Unix socket which have only two arguments in which the first argument is the path and the second argument is the optional argument which listen to the listening event. server.close([callback]) - No other new connections are accepted by utilizing the server.close() function and the server gets closed only after all the existing servers are closed. The function have only one argument “callback” which is an optional argument and is executed only after the close event emitted successfully. server.setTimeout(msecs, callback) - A timeout value is given to the socket created by server by using this function. When the socket of client is idle for the given time then the timeout event is emitted by the server. The function have two arguments as follows. The listener must and should handle the timeout socket when there is a listener for the timeout event, if there is no timeout event the timeout socket get demolished.

shape Example

The HTTP server is easy to create in Node.js, the example below demonstrate creating an HTTP server which handles the request and response in Node.js First create a .js file with code shown below. httpServer.js [c] var http = require('http'); var server = http.createServer(function (req, res) { if (req.url == '/') { res.writeHead(200, { 'Content-Type': 'text/html' }); res.write('<html><body><h1>SPLessons home Page.</h1></body></html>'); res.end(); } else if (req.url == "/login") { res.writeHead(200, { 'Content-Type': 'text/html' }); res.write('<html><body><p>SPLessons Login Page.</p></body></html>'); res.end(); } else if (req.url == "/admin") { res.writeHead(200, { 'Content-Type': 'text/html' }); res.write('<html><body><p>SPLessons admin Page.</p></body></html>'); res.end(); } else res.end('Request Invalid!'); }); server.listen(3000); console.log('Node.js web server at port 3000 is running..') [/c]

shape Output

Compiling the above code will produce the output as shown in the image below. Now, open the browser and point the browser to http://localhost:3000 and look at the result which would be as shown in the image below. Now, point the browser to http://localhost:3000/login, reload the browser and look at the result which would be as shown in the image below. Now, point the browser to http://localhost:3000/admin, reload the browser and look at the result which would be as shown in the image below.

Reading POST request

shape Description

The data reading from a POST request is difficult in Node.js but it can be made easy by listening to the data. Initially listen the incoming data and then wait for the data to finish by which the data can be processed without losing anything. The example below demonstrate the code which read the data from a POST request. POST.js [c] var http = require('http'); var uhtml = '<html><head><title>Post Request Example</title></head>' + '<body>' + '<p>Input name and Address</p>'+ '<form method="post">' + 'Name : <input name="name" size=20><br>' + 'Address : <input name="address" size=50><br>' + '<input type="submit">' + '</form>' + '</body></html>'; http.createServer(function (req, res) { var body = ""; req.on('data', function (chunk) { body += chunk; }); req.on('end', function () { console.log('Data submitted: ' + body); res.writeHead(200); res.end(uhtml); }); }).listen(5000); [/c] Compiling the above code, open and point the browser to http//:localhost:5000, then the produced output would be as shown in the image below. Fill the name and address from the obtained output and click on submit button as indicated in the above image. Now, come back to the Node terminal and look at the result which would be as shown in the image below. The server listens to the request and send the responds, from the above output there are few line with empty data i.e Data Submitted:  and this happens because of regular GET requests go through the similar code path.

Summary

shape Key Points

  • The web server process the request through HTTP
  • The common use of a web server is to host the websites
  • The foundation for the data communication for the World Wide Web depends on HTTP.
  • The Node.js HTTP Module is built with various functions and events to create a web server.