Node http module

The http module of Node.js provides useful functions and classes to build an HTTP server

The HTTP core module is the key module of the Node network.

can use

const http = require('http')

This module provides some attributes and methods and some classes.

characteristic

http.METHODS

This attribute lists all 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 attribute lists all 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

Point to the global instance of the Agent object, which ishttp.Agentclass.

It is used to manage the connection persistence and reuse of HTTP clients, and it is a key component of the Node HTTP network.

more contenthttp.AgentThe class is described later.

method

http.createServer()

Return a new instancehttp.Serverclass.

usage:

const server = http.createServer((req, res) => {
  //handle every single request with this callback
})

http.request()

Make an HTTP request to the server and create an instancehttp.ClientRequestclass.

http.get()

ashttp.request(), But will automatically set the HTTP method to GET and callreq.end()automatically.

class

The HTTP module provides 5 categories:

  • http.Agent
  • http.ClientRequest
  • http.Server
  • http.ServerResponse
  • http.IncomingMessage

http.Agent

Node creates a global instancehttp.AgentClass, used to manage the connection persistence and reuse of the HTTP client (a key component of the Node HTTP network).

This object ensures that every request to the server is queued and a single socket is reused.

It also maintains a socket pool. For performance reasons, this is the key.

http.ClientRequest

Onehttp.ClientRequestWhen the object was createdhttp.request()orhttp.get()Called.

After receiving the response,responseInvoke events by respondinghttp.IncomingMessageThe instance is used as a parameter.

The returned data of the response can be read in two ways:

  • You can callresponse.read()method
  • insideresponseEvent handler, you candataEvent, so you can listen to the data flowing into it.

http.Server

This class is usually instantiated and returned when a new server is created.http.createServer().

Once you have the server object, you can access its methods:

  • close()Prevent the server from accepting new connections
  • listen()Start the HTTP server and listen for connections

http.ServerResponse

Created byhttp.ServerAnd passed as the second parameter torequestIn the event of a fire.

Well known and used in coderes:

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

The method you will always call in the handler isend(), It will close the response, the message is complete, and the server can send it to the client. It must be called on every response.

These methods are used to interact with HTTP headers:

  • getHeaderNames()Get a list of the names of the HTTP headers that have been set
  • getHeaders()Get a copy of the HTTP headers that have been set
  • setHeader('headername', value)Set HTTP header value
  • getHeader('headername')Get the HTTP header that has been set
  • removeHeader('headername')Delete the HTTP headers that have been set
  • hasHeader('headername')Return true if the header is set in the response
  • headersSent()Return true if the header has been sent to the client

After processing the header, you can send it to the client by callingresponse.writeHead(), It accepts statusCode as the first parameter, optional status message and header object.

To send data to the client in the response body, usewrite(). It sends the buffered data to the HTTP response stream.

If you haven’t sent the header yet, useresponse.writeHead(), It will first send the header, as well as the status code and message set in the request, you can setstatusCodewithstatusMessageProperty value:

response.statusCode = 500
response.statusMessage = 'Internal Server Error'

http.IncomingMessage

Onehttp.IncomingMessageThe object was created by:

  • http.ServerWhen listeningrequestevent
  • http.ClientRequestWhen listeningresponseevent

It can be used to access the response:

  • Use its statestatusCodewithstatusMessagemethod
  • Header uses itsheadersMethod orrawHeaders
  • HTTP method usagemethodmethod
  • HTTP version usehttpVersionmethod
  • Use URLurlmethod
  • Underlying socket usagesocketmethod

Use streams to access data becausehttp.IncomingMessageImplement the Readable Stream interface.

Download mine for freeNode.js manual


More node tutorials: