Just a few weeks until the 2021 JavaScript Full-Stack Bootcamp opens.
Signup to the waiting list!
The HTTP core module is a key module to Node networking.
It can be included using
const http = require('http')
The module provides some properties and methods, and some classes.
Properties
http.METHODS
This property lists all the HTTP methods supported:
> 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 description:
> 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
Points to the global instance of the Agent object, which is an instance of the http.Agent
class.
It’s used to manage connections persistance and reuse for HTTP clients, and it’s a key component of Node HTTP networking.
More in the http.Agent
class description later on.
Methods
http.createServer()
Return a new instance of the http.Server
class.
Usage:
const server = http.createServer((req, res) => {
//handle every single request with this callback
})
http.request()
Makes an HTTP request to a server, creating an instance of the http.ClientRequest
class.
http.get()
Similar to http.request()
, but automatically sets the HTTP method to GET, and calls req.end()
automatically.
Classes
The HTTP module provides 5 classes:
http.Agent
http.ClientRequest
http.Server
http.ServerResponse
http.IncomingMessage
http.Agent
Node creates a global instance of the http.Agent
class to manage connections persistance and reuse for HTTP clients, a key component of Node HTTP networking.
This object makes sure that every request made to a server is queued and a single socket is reused.
It also maintains a pool of sockets. This is key for performance reasons.
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, with an http.IncomingMessage
instance as argument.
The returned data of a response can be read in 2 ways:
- you can call the
response.read()
method - in the
response
event handler you can setup an event listener for thedata
event, so you can listen for the data streamed into.
http.Server
This class is commonly instantiated and returned when creating a new server using http.createServer()
.
Once you have a server object, you have access to its methods:
close()
stops the server from accepting new connectionslisten()
starts the HTTP server and listens for connections
http.ServerResponse
Created by an http.Server
and passed as the second parameter to the request
event it fires.
Commonly known and used in code as res
:
const server = http.createServer((req, res) => {
//res is an http.ServerResponse object
})
The method you’ll always call in the handler is end()
, which closes the response, the message is complete and the server can send it to the client. It must be called on each response.
These methods are used to interact with HTTP headers:
getHeaderNames()
get the list of the names of the HTTP headers already setgetHeaders()
get a copy of the HTTP headers already setsetHeader('headername', value)
sets an HTTP header valuegetHeader('headername')
gets an HTTP header already setremoveHeader('headername')
removes an HTTP header already sethasHeader('headername')
return true if the response has that header setheadersSent()
return true if the headers have already been sent to the client
After processing the headers you can send them to the client by calling response.writeHead()
, which accepts the statusCode as the first parameter, the optional status message, and the headers object.
To send data to the client in the response body, you use write()
. It will send buffered data to the HTTP response stream.
If the headers were not sent yet using response.writeHead()
, it will send the headers first, with the status code and message that’s set in the request, which you can edit by setting the statusCode
and statusMessage
properties values:
response.statusCode = 500
response.statusMessage = 'Internal Server Error'
http.IncomingMessage
An http.IncomingMessage
object is created by:
http.Server
when listening to therequest
eventhttp.ClientRequest
when listening to theresponse
event
It can be used to access the response:
- status using its
statusCode
andstatusMessage
methods - headers using its
headers
method orrawHeaders
- HTTP method using its
method
method - HTTP version using the
httpVersion
method - URL using the
url
method - underlying socket using the
socket
method
The data is accessed using streams, since http.IncomingMessage
implements the Readable Stream interface.
Download my free Node.js Handbook
The 2021 JavaScript Full-Stack Bootcamp will start at the end of March 2021. Don't miss this opportunity, signup to the waiting list!
More node tutorials:
- An introduction to the npm package manager
- Introduction to Node.js
- HTTP requests using Axios
- Where to host a Node.js app
- Interact with the Google Analytics API using Node.js
- The npx Node Package Runner
- The package.json guide
- Where does npm install the packages?
- How to update Node.js
- How to use or execute a package installed using npm
- The package-lock.json file
- Semantic Versioning using npm
- Should you commit the node_modules folder to Git?
- Update all the Node dependencies to their latest version
- Parsing JSON with Node.js
- Find the installed version of an npm package
- Node.js Streams
- Install an older version of an npm package
- Get the current folder in Node
- How to log an object in Node
- Expose functionality from a Node file using exports
- Differences between Node and the Browser
- Make an HTTP POST request using Node
- Get HTTP request body data using Node
- Node Buffers
- A brief history of Node.js
- How to install Node.js
- How much JavaScript do you need to know to use Node?
- How to use the Node.js REPL
- Node, accept arguments from the command line
- Output to the command line using Node
- Accept input from the command line in Node
- Uninstalling npm packages with `npm uninstall`
- npm global or local packages
- npm dependencies and devDependencies
- The Node.js Event Loop
- Understanding process.nextTick()
- Understanding setImmediate()
- The Node Event emitter
- Build an HTTP Server
- Making HTTP requests with Node
- The Node fs module
- HTTP requests in Node using Axios
- Reading files with Node
- Node File Paths
- Writing files with Node
- Node file stats
- Working with file descriptors in Node
- Working with folders in Node
- The Node path module
- The Node http module
- Using WebSockets with Node.js
- The basics of working with MySQL and Node
- Error handling in Node.js
- The Pug Guide
- How to read environment variables from Node.js
- How to exit from a Node.js program
- The Node os module
- The Node events module
- Node, the difference between development and production
- How to check if a file exists in Node.js
- How to create an empty file in Node.js
- How to remove a file with Node.js
- How to get the last updated date of a file using Node.js
- How to determine if a date is today in JavaScript
- How to write a JSON object to file in Node.js
- Why should you use Node.js in your next project?
- Run a web server from any folder
- How to use MongoDB with Node.js
- Use the Chrome DevTools to debug a Node.js app
- What is pnpm?
- The Node.js Runtime v8 options list
- How to fix the "Missing write access" error when using npm
- How to enable ES Modules in Node.js
- How to spawn a child process with Node.js
- How to get both parsed body and raw body in Express
- How to handle file uploads in Node.js
- What are peer dependencies in a Node module?
- How to write a CSV file with Node.js
- How to read a CSV file with Node.js
- The Node Core Modules
- Incrementing multiple folders numbers at once using Node.js
- How to print a canvas to a data URL
- How to create and save an image with Node.js and Canvas
- How to download an image using Node.js
- How to mass rename files in Node.js
- How to get the names of all the files in a folder in Node
- How to use promises and await with Node.js callback-based functions
- How to test an npm package locally
- How to check the current Node.js version at runtime
- How to use Sequelize to interact with PostgreSQL
- Serve an HTML page using Node.js
- How to solve the `util.pump is not a function` error in Node.js