Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Command to Include Node.js HTTP Module
3.
Node.js HTTP Module Properties
3.1.
1. http.METHODS
3.2.
2. http.STATUS_CODES
3.3.
3. http.globalAgent()
4.
Node.js HTTP Module Methods
5.
Node.js HTTP Module Classes
5.1.
1. HTTP.Agent
5.2.
2. http.ClientRequest
5.3.
3. HTTP.Server
5.4.
4. http.ServerResponse
5.5.
5. http.IncomingMessage
6.
Frequently Asked Questions:
6.1.
What is HTTP server module?
6.2.
How to start an HTTP server with HTTP module?
6.3.
What is HTTP in JavaScript?
6.4.
Why is request response used in HTTP module?
7.
Conclusion
Last Updated: May 23, 2024
Easy

Node.js HTTP Module

Leveraging ChatGPT - GenAI as a Microsoft Data Expert
Speaker
Prerita Agarwal
Data Specialist @
23 Jul, 2024 @ 01:30 PM

Introduction

The Node.js HTTP module is a fundamental component for building web applications and services using Node.js. It provides a set of powerful tools and functions that enable developers to create HTTP servers and handle requests and responses efficiently. With the HTTP module, you can easily set up a server, define routes, process incoming data, and send responses back to clients. 

Node.js HTTP Module

Command to Include Node.js HTTP Module

Node.js HTTP module can be included using the following command:

const http = require('http')
Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Node.js HTTP Module Properties

Let us discuss the properties of the Node.js HTTP module:

1. http.METHODS

This is the property that lists all the HTTP methods.

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

 

2. http.STATUS_CODES

It is used to list HTTP status codes and descriptions. 

> require('http').STATUS_CODES
{ '100': 'Continue',
  '101': 'Switching Protocols',
  '102': 'Processing',
  '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': 'Unordered Collection',
  '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' }

 

3. http.globalAgent()

It maintains a queue of pending requests for each host and port. It reuses the same socket until the queue is empty. 

Node.js HTTP Module Methods

Let us talk about the methods of the Node.js HTTP module:

MethodDescription
http.createServer()Creates a new HTTP server instance.
server.listen()Binds and listens for connections on the specified host and port.
server.close()Stops the server from accepting new connections and closes existing connections.
server.setTimeout()Sets the timeout value for sockets, controlling how long the server should wait for the next request.
request.on()Attaches event listeners to the request object to handle events such as data, end, and error.
response.writeHead()Sends a response header to the request, including the status code and headers.
response.write()Sends a chunk of the response body. This method can be called multiple times to send multiple chunks of the response.
response.end()Signals to the server that all response headers and body have been sent, ending the response process.
response.setHeader()Sets a single header value for the response.
response.getHeader()Retrieves the value of a single response header.
response.removeHeader()Removes a header from the response.
response.statusCodeSets or retrieves the HTTP status code of the response.
http.request()Makes an HTTP request to a specified URL.
http.get()Sends a GET request to a specified URL and returns a response.

Node.js HTTP Module Classes

Let us talk about the classes of the Node.js  HTTP module:

1. HTTP.Agent

It manages connection persistence and reuses for HTTP clients. It does this by storing the pending requests in a queue and reusing a single socket connection until the queue is empty. It also maintains a pool of sockets to improve performance.

The http.globalAgent points to the global instance of the Agent object, which is an instance of the http.Agent class.

2. http.ClientRequest

It is created when HTTP.request() or HTTP.get() is called. After receiving the response, the response event is called with the response, with HTTP.IncomingMessage as arguments.

There are two ways to read the returned data:

  1. Calling the response.read() method.
  2. In the response event handler, an event listener can be set up for the data event so that the user can listen for the data streamed into.

3. HTTP.Server

This class is generally created as an instance while creating a new server using HTTP.createServer().

Methods of server object:

  • listen(): which is used for starting HTTP server and accepting responses.
  • close(): which is used for stopping the server from accepting responses.

4. http.ServerResponse

It is created by the http.Server and passed as a second argument to the request function.

Example:

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

Some ServerResponse methods and properties:

Methods

Properties

addTrailers()adding HTTP trailing headers
end()Signaling the server that the response is complete
finishedReturning true for complete response, otherwise false.
getHeader()Returning specified header value
headersSentReturning true if headers were the sent, otherwise false,
removeHeader()Removes the specified header
setHeader()Setting the specified header
setTimeoutSetting the timeout value of the socket to the specified number of milliseconds
statusMessageSets the status message that will be sent to the client
write()Sends text, or a text stream, to the client
writeContinue()Sends a HTTP Continue message to the client
writeHead()It sends status and response headers to the clients.
sendDateIt is set to true by default. Users can set it to false if the date header is not to be included in the response.
statusCodeIt sets the status code that is to be sent to the client.

5. http.IncomingMessage

It represents the request to the server. 

http.IncomingMessage object can be created by:

  1. http.Server when listening to the request event
  2. http.ClientRequest when listening to the response event

Some IncomingMessage methods and properties:

Methods

Properties

headersIt returns a key-value pair object containing header names and values.
rawHeadersReturns array of request headers
httpVersionSpecifies HTTP version sent by the client.
setTimeout()We can specify the time limit after we want to call a specific function.
statusCodeTells the HTTP response status code
URLReturns request URL string
trailersReturns object containing the trailer
methodReturns request method
socketReturns socket object for connection
rawTrailersReturns array of raw request trailer keys and values

Frequently Asked Questions:

What is HTTP server module?

The HTTP server module in Node.js allows developers to create and manage web servers. It provides functionalities to handle HTTP requests and responses, enabling the development of web applications and services.

How to start an HTTP server with HTTP module?

To start an HTTP server with the HTTP module, use http.createServer() to create the server and server.listen() to bind it to a specific port, allowing it to listen for incoming requests.

What is HTTP in JavaScript?

HTTP in JavaScript refers to the protocol used for communication between clients and servers over the web. JavaScript can handle HTTP requests and responses, enabling web applications to interact with web servers.

Why is request response used in HTTP module?

The request-response model in the HTTP module is used to manage the interaction between clients and servers. It allows servers to process client requests, perform necessary actions, and send appropriate responses back to clients.

Conclusion

In this blog, we discussed the Node.js HTTP module. This module is a powerful tool for building and managing web servers and applications. By providing essential methods and functionalities for handling HTTP requests and responses, it simplifies the process of creating robust and scalable web solutions. 

If you are preparing for your next web development interview, check out the blogs, 25 CSS Interview Questions, and 30 JavaScript interview questions.

Live masterclass