Node.js HTTP Module

An Introduction to HTTP Module

The http module is a core module in Node.js that uses the Hypertext Transfer Protocol (HTTP) to transfer data. With the help of the http module, we can build HTTP servers that listen on a specified port and send the response back to the Client.

To import the http module in Node.js, we would be using the require() function as follows:

const http = require(‘http’);

Some fundamental properties of HTTP Module

Some of the basic properties of the Node.js http module are listed below:

1. http.METHODS

The http.METHODS property is used to list all the HTTP methods that are supported in Node.js for networking.

> require('http').METHODS
[
  'ACL', 'BIND', 'CHECKOUT',
'CONNECT', 'COPY', 'DELETE',  
  'GET', 'HEAD', 'LINK',    
  'LOCK', 'M-SEARCH', 'MERGE',  
  'MKACTIVITY', 'MKCALENDAR', 'MKCOL',
  'MOVE', 'NOTIFY', 'OPTIONS',
  'PATCH', 'POST', 'PRI',
'PROPFIND', 'PROPPATCH', 'PURGE',
  'PUT', 'REBIND', 'REPORT',
  'SEARCH', 'SOURCE', 'SUBSCRIBE',
  'TRACE', 'UNBIND', 'UNLINK',
  'UNLOCK', 'UNSUBSCRIBE'
]

2. http.globalAgent

The http.globalAgent is a global object of the http.Agent class, which is utilized for all the HTTP client requests by default. It is used to control connections persistence, and reuse for HTTP clients. Moreover, it is a significant constituent in Node.js HTTP networking.

3. http.STATUS_CODES

The http.STATUS_CODES property is used to list all the standard HTTP response status codes with their descriptions in short.

> require('http').STATUS_CODES
{
  '100': 'Continue',
  '101': 'Switching Protocols',
  '102': 'Processing',
  '103': 'Early Hints',
  '200': 'OK',
  '201': 'Created',
  '202': 'Accepted',
  '203': 'Non-Authoritative Information',
  '204': 'No Content',
  '205': 'Reset Content',
  '206': 'Partial Content',
  '207': 'Multi-Status',
  '208': 'Already Reported',
  '226': 'IM Used',
  '300': 'Multiple Choices',
  '301': 'Moved Permanently',
  '302': 'Found',
  '303': 'See Other',
  '304': 'Not Modified',
  '305': 'Use Proxy',
  '307': 'Temporary Redirect',
  '308': 'Permanent Redirect',
  '400': 'Bad Request',
  '401': 'Unauthorized',
  '402': 'Payment Required',
  '403': 'Forbidden',
  '404': 'Not Found',
  '405': 'Method Not Allowed',
  '406': 'Not Acceptable',
  '407': 'Proxy Authentication Required',
  '408': 'Request Timeout',
  '409': 'Conflict',
  '410': 'Gone',
  '411': 'Length Required',
  '412': 'Precondition Failed',
  '413': 'Payload Too Large',
  '414': 'URI Too Long',
  '415': 'Unsupported Media Type',
  '416': 'Range Not Satisfiable',
  '417': 'Expectation Failed',
  '418': "I'm a Teapot",
  '421': 'Misdirected Request',
  '422': 'Unprocessable Entity',
  '423': 'Locked',
  '424': 'Failed Dependency',
  '425': 'Too Early',
  '426': 'Upgrade Required',
  '428': 'Precondition Required',
  '429': 'Too Many Requests',
  '431': 'Request Header Fields Too Large',
  '451': 'Unavailable For Legal Reasons',
  '500': 'Internal Server Error',
  '501': 'Not Implemented',
  '502': 'Bad Gateway',
  '503': 'Service Unavailable',
  '504': 'Gateway Timeout',
  '505': 'HTTP Version Not Supported',
  '506': 'Variant Also Negotiates',
  '507': 'Insufficient Storage',
  '508': 'Loop Detected',
  '509': 'Bandwidth Limit Exceeded',
  '510': 'Not Extended',
  '511': 'Network Authentication Required'
}

Fundamental methods of Node.js HTTP module

There are various methods used in the Node.js HTTP module to create a web server and process in HTTP networking. Some of them are as follows:

1. http.createServer()

The http.createServer() method returns a new object of http.server class. Here’s a demonstration to use this method:

const server = http.createServer((req, res) => {
    // This Callback function will handle each and every single request
});

2. http.request()

The http.request() method is used to make an HTTP request to a server, building an object of the http.ClientRequest class.

3. http.get()

The http.get() method is similar to http.request(), however the process of setting the HTTP method is GET, and calling req.end() is automatic.

Classes of Node.js HTTP module

There are five classes that the HTTP module provides:

1. http.Agent

Node.js creates a global object of the http.Agent class to handle the network's perseverance and reprocess for HTTP clients, a significant constituent of Node.js HTTP networking. This instance makes sure that each and every request made to a server is lined-up, and a solitary socket is reprocessed.

It also sustains a pool of sockets. This is the significance of execution goals.

2. http.Server

The http.Server class is used to act as an object, which is returned when building a new server with the help of http.createServer() method.

There are some methods, which comes under the server object and activates while in use:

  • The http.Server class provides the user a method named close(), which is used to resist the server from accepting an new network.
  • The http.Server class also provides the listen() method, that is used to initiate the HTTP server and listens for the connections

3. http.ClientRequest

The http.ClientRequest class is built when http.get() or http.request() is called. The response event is returned, when a response is received, with an argument namely, http.IncomingMessage instance.

There are two ways to read the data returned from the response:

  • We can call the response.read() method.
  • We can set up an event listener to listen for the information streamed into, in the response event handler.

4. http.ServerResponse

The http.ServerResponse class is constructed by an http.Server class. It is delivered as the second parameter to the request event it activates. It is commonly utilized and called in code as a res. A res is an object of the http.ServerResponse class.

const server = http.createServer((req, res) => {
    // res is an object of http.ServerResponse class
});

The end method is constantly called in the handler, which helps respond to 'close' when the message is completed. Then the server sends it to the client. The point is to be noted that it should be called on every response.

Moreover, these methods are utilized for cooperating with the HTTP headers:

  • The getHeaders() method is used to obtain a replica of the HTTP headers set already.
  • The setHeader('headername', value) method is used to place an HTTP header value.
  • The hasHeader('headername') method returns a Boolean value if the response has a header set or not.
  • The getHeaderNames() method provides the list of the HTTP headers' names already set.
  • The removeHeader('headername') method is used to remove an HTTP header, which is set already.
  • The getHeader('headername') method is used to get an HTTP header which is set already.
  • The headersSent() method returns a Boolean value if the headers have been sent already to the client or not.

5. http.IncomingMessage

The http.IncomingMessage class is constructed by the http.Server and http.ClientRequest and delivered as the first argument to the 'request' event and the 'response' event, respectively.

The http.IncomingMessage class can be utilized to access the response like:

  • Status with the help of themessage.statusMessage and message.statusCode methods.
  • Headers with the help of the message.headers method or message.rawHeaders method.
  • HTTP method with the help of the message.method method
  • HTTP version with the help of the message.httpVersion method
  • URL with the help of the message.url method
  • Underlying socket with the help of the message.socket method

The info is accessed with the help of streams, as the http.IncomingMessage class applies the Readable Stream interface.

Creating a Node.js Web Server

In Node.js, we can create a simple web server using the http modules and its methods. Let's see an example given below to understand how a basic Node.js Web Server looks and how it works.

File: myserver.js

// Importing the 'http' module
const http = require('http');
// Declaring the port
const host = 'localhost';
const port = 8080;
// Creating the server
const server = http.createServer((req, res) => {
  res.statusCode = 200;
  res.setHeader('Content-Type', 'text/html');
  res.end('<h1>This is my first web server</h1>');
});
server.listen(port, host, () => {
  console.log("The Server is running on http://" + host + ":" + port);
});

In the above program, we’ve imported the http module using the require() function. Then, we have assigned a host and port to which our Server listens. In the next line, we have created a server using the method http.createServer(), which will listen to the request (req) and response (res) on the port number, i.e., 8080.

Let’s execute the following script file to see the Output:

$ node myserver.js

The Output should look as follows:

The Server is running on http://localhost:8080

The above output shows that the Server has been started on the localhost with port number 8080. To check if the server is running or not, we can copy the link: http://localhost:8080 and paste it on any web browser. The final Output should be seen as given below:

Node.js HTTP Module

Thus, a Node.js web server has been created successfully.