Node.js HTTP Module
Introduction:
A module is a set of functions that can be included in the application. They are very similar to JavaScript libraries. Some modules are built-in modules that can be used without any installation, and some modules have to be installed.
Node.js HTTP module is the built-in module of node.js, which allows it to transfer data to HTTP(HyperText Transfer Protocol).
Node.js HTTP module can be included using the following command:
const http = require('http')
Node.js HTTP module properties:
Let us discuss the properties of the Node.js HTTP module:
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' ]
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' }
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:
http.createServer()
It is used to return a new instance of the HTTP server class.
Command:
const server = http.createServer((req, res) => {
// Handle every single request with this callback
})
http.request()
It is used to make an HTTP request to the server.
Check out the blog making HTTP requests with node.js to know more.
http.get()
It is similar to HTTP.request(). It automatically sets the HTTP method to GET. The GET method gets the data from a particular source. It calls req.end() automatically, which ends the response process.
Check out the blog get HTTP request body data using node.js to know more.
Node.js HTTP module Classes:
Let us talk about the classes of the Node.js HTTP module:
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.
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:
- Calling the response.read() method.
- 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.
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.
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 |
finished | Returning true for complete response, otherwise false. |
getHeader() | Returning specified header value |
headersSent | Returning true if headers were the sent, otherwise false, |
removeHeader() | Removes the specified header |
setHeader() | Setting the specified header |
setTimeout | Setting the timeout value of the socket to the specified number of milliseconds |
statusMessage | Sets 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. |
sendDate | It is set to true by default. Users can set it to false if the date header is not to be included in the response. |
statusCode | It sets the status code that is to be sent to the client. |
http.IncomingMessage
It represents the request to the server.
http.IncomingMessage object can be created by:
- http.Server when listening to the request event
- http.ClientRequest when listening to the response event
Some IncomingMessage methods and properties:
Methods | Properties |
headers | It returns a key-value pair object containing header names and values. |
rawHeaders | Returns array of request headers |
httpVersion | Specifies HTTP version sent by the client. |
setTimeout() | We can specify the time limit after we want to call a specific function. |
statusCode | Tells the HTTP response status code |
URL | Returns request URL string |
trailers | Returns object containing the trailer |
method | Returns request method |
socket | Returns socket object for connection |
rawTrailers | Returns array of raw request trailer keys and values |
Frequently Asked Questions:
1. What are core modules in node.js?
Ans-> core modules provide basic functionalities of the web applications. They are HTTP, util, fs, URL, query-string, stream, zlib.
2. What are local modules in node.js?
Ans-> They are created locally in the node.js application. They include functionalities of our application in separate files.
3. What are third-party modules in node.js?
Ans-> These are the modules that the third party writes. That is, they are pieces of code written by others that users can incorporate.
4. What are the various methods used to interact with HTTP headers?
Ans-> The methods used to interact with HTTP headers are request.flushHeader, request.getHeader, request.getRawHeaderNames, request.MaxHeadersCount, request.removeHeaders, etc.
Key Takeaways:
In this blog, we discussed the Node.js HTTP module. We talked about its properties, methods, and classes.
Readers, if you liked this blog, you can learn more about Node.js from here.
If you are preparing for your next web development interview, check out the blogs, 25 CSS Interview Questions, and 30 JavaScript interview questions.