The http module in Node.js is a powerful tool for building HTTP servers. With its useful functions and classes, developers can easily create and manage networking applications.
Including the http module in your Node.js project is simple:
const http = require('http');
The http module provides several properties, methods, and classes that are essential for building HTTP servers. Let’s explore them in detail.
Properties
http.METHODS
This property lists all the supported 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
This property lists all the HTTP status codes and their 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
This property points to the global instance of the Agent object, which is an instance of the http.Agent
class. It is used to manage connection persistence and reuse for HTTP clients and plays a crucial role in Node HTTP networking.
Methods
http.createServer()
This method returns a new instance of the http.Server
class. It accepts a callback function that will be called for every incoming request.
const server = http.createServer((req, res) => {
// Handle every single request with this callback
});
http.request()
The http.request()
method makes an HTTP request to a server and creates an instance of the http.ClientRequest
class.
http.get()
Similar to http.request()
, the http.get()
method automatically sets the HTTP method to GET and automatically calls req.end()
.
Classes
The http module provides five classes:
http.Agent
Node creates a global instance of the http.Agent
class to manage connection persistence and reuse for HTTP clients. This class is key to improving performance in Node HTTP networking.
The http.Agent
object ensures that every request made to a server is queued and a single socket is reused. It also maintains a pool of sockets.
http.ClientRequest
An http.ClientRequest
object is created when http.request()
or http.get()
is called. When a response is received, the response
event is called with the response and an http.IncomingMessage
instance as an argument.
To access the data returned in the response, you can either call the response.read()
method or set up an event listener for the data
event in the response
event handler.
http.Server
The http.Server
class is commonly instantiated and returned when creating a new server using http.createServer()
. Once you have a server object, you can use its methods:
close()
: Stops the server from accepting new connections.listen()
: Starts the HTTP server and listens for connections.
http.ServerResponse
An http.ServerResponse
object is created by an http.Server
when the request
event is fired. It is commonly known and used in code as res
. You can call the end()
method on the http.ServerResponse
object to close the response and send it to the client. Other useful methods for interacting with HTTP headers include getHeaderNames()
, getHeaders()
, setHeader()
, getHeader()
, removeHeader()
, hasHeader()
, and headersSent()
.
http.IncomingMessage
An http.IncomingMessage
object is created when listening to the request
event on an http.Server
or the response
event on an http.ClientRequest
. It provides various methods to access the response, such as statusCode()
, headers()
, method()
, httpVersion()
, url()
, and socket()
. The data can be accessed through streams, as http.IncomingMessage
implements the Readable Stream interface.
These are the essential components of the http module in Node.js. By leveraging these properties, methods, and classes, developers can efficiently build and manage HTTP servers in their Node.js applications.
Tags: Node.js, HTTP, Networking