NodeJS study Notes-Http Module _ node. js

Source: Internet
Author: User
Tags node server
Here we are only familiar with the http Module API in nodejs. we generally use a third-party framework, such as Express, during the development process. It encapsulates more simple APIs for building http servers. I. opening analysis

First of all, we should be familiar with the concept of "Http". it is not based on a specific language. it is a common application layer protocol. Different languages have different implementation details, but it never changes, the idea is the same,

As a host running environment, NodeJS uses JavaScript as the host language and has its own set of standards. in this article, let's take a look at the "Http Module ". But as a premise,

I hope you can read the APIs provided on the official website and get a pre-knowledge. this is much more convenient. The following is an overview of the Http APIs:

The code is as follows:

Http. createServer ([requestListener])
Http. createClient ([port], [host])
Class: http. Server
Event: 'request'
Event: 'connection'
Event: 'close'
Event: 'checkcontinue'
Event: 'Connect'
Event: 'upgrade'
Event: 'clientror'
Server. listen (port, [hostname], [backlog], [callback])
Server. listen (path, [callback])
Server. listen (handle, [callback])
Server. close ([callback])
Server. maxHeadersCount
Server. setTimeout (msecs, callback)
Server. timeout
Class: http. ServerResponse
Event: 'close'
Response. writeContinue ()
Response. writeHead (statusCode, [reasonPhrase], [headers])
Response. setTimeout (msecs, callback)
Response. statusCode
Response. setHeader (name, value)
Response. headersSent
Response. sendDate
Response. getHeader (name)
Response. removeHeader (name)
Response. write (chunk, [encoding])
Response. addTrailers (headers)
Response. end ([data], [encoding])
Http. request (options, callback)
Http. get (options, callback)
Class: http. Agent
New Agent ([options])
Agent. maxSockets
Agent. maxFreeSockets
Agent. sockets
Agent. freeSockets
Agent. requests
Agent. destroy ()
Agent. getName (options)
Http. globalAgent
Class: http. ClientRequest
Event 'Response'
Event: 'socket'
Event: 'Connect'
Event: 'upgrade'
Event: 'contine'
Request. write (chunk, [encoding])
Request. end ([data], [encoding])
Request. abort ()
Request. setTimeout (timeout, [callback])
Request. setNoDelay ([noDelay])
Request. setSocketKeepAlive ([enable], [initialDelay])
Http. IncomingMessage
Event: 'close'
Message. httpVersion
Message. headers
Message. rawHeaders
Message. trailers
Message. rawTrailers
Message. setTimeout (msecs, callback)
Message. method
Message. url
Message. statusCode
Message. socket

Let's start with a simple example to create a file named server. js and write the following code:

The code is as follows:

Var http = require ('http ');
Var server = http. createServer (function (req, res ){
Res. writeHeader (200 ,{
'Content-type': 'Text/plain; charset = utf-8 '// add charset = utf-8
Res. end ("Hello, Big Bear! ");
Server. listen (8888 );
Console. log ("http server running on port 8888 ...");

(Node server. js) The following is the running result:

II. detail analysis example

Take a look at this small example:

(Line 1): use "require" to introduce the "http" module that comes with NodeJS and assign it to the http variable.

(Line 2): Call the function "createServer" provided by the http module ". This function returns a new web server object.

The parameter "requestListener" is a function that is automatically added to the listener queue of the "request" event.

When a request arrives, Event-Loop will put the Listener callback function into the execution queue, and all the code in node will be executed one by one from the execution queue.

These executions are all on the working thread (Event Loop itself can be considered to be in an independent thread, we generally do not mention this thread, but call node as a single-threaded execution environment ),

All callbacks are run on a worker thread.

Let's take a look at the callback function "requestListener". It provides two parameters (request, response ),

Triggered every time a request is received. Note that each connection may have multiple requests (in the keep-alive connection ).

"Request" is an instance of http. IncomingMessage. "Response" is an instance of http. ServerResponse.

An http request object is a readable stream, while an http response object is a writable stream.

An "IncomingMessage" object is created by http. Server or http. ClientRequest,

And passed as the first parameter to the "request" and "response" events respectively.

It can also be used to access the response status, header files, and data.

It implements the "Stream" interface and the following additional events, methods, and attributes. (For details, refer to the api ).

(3 rows): "writeHeader". use the "response. writeHead ()" function to send an Http status 200 and content type of the Http header ).

Returns the response header to the request. "StatusCode" is a three-digit HTTP status code, such as 404. The last parameter, "headers", is the content of the response header.


The code is as follows:

Var body = 'Hello World ';
Response. writeHead (200 ,{
'Content-length': body. Length,
'Content-type': 'Text/plain'

Note: Content-Length is calculated in bytes instead of character.

The reason for the previous example is that the string "Hello World !" It only contains single-byte characters.

If the body contains multi-byte characters, you should use Buffer. byteLength () to determine the number of bytes of the string in the case of multi-byte character encoding.

It should be further noted that Node does not check whether the Content-Lenth attribute matches the transmitted body length.

StatusCode is a three-digit HTTP status code, for example, "404 ". Here we will talk about "http. STATUS_CODES". The set and brief description of all standard "Http" response status codes are included.

Source code reference:

The code is as follows:

100: 'contine ',
101: 'Switching protocols ',
102: 'processing', // RFC 2518, obsoleted by RFC 4918
200: 'OK ',
201: 'created ',
202: 'accessted ',
203: 'Non-Authoritative information ',
204: 'nocontent ',
205: 'reset content ',
206: 'partial content ',
207: 'multi-status', // RFC 4918
300: 'Multiple choices ',
301: 'moved Permanently ',
302: 'moved Temporarily ',
303: 'See Other ',
304: 'Not modified ',
305: 'Use proxy ',
307: 'temporary redirect ',
400: 'bad request ',
401: 'authorized ',
402: 'payment required ',
403: 'Forbidden ',
404: 'not Found ',
405: 'Method Not allowed ',
406: 'Not accesstable ',
407: 'proxy Authentication required ',
408: 'request Time-out ',
409: 'refresh ',
410: 'gione ',
411: 'length required ',
412: 'precondition failed ',
413: 'request Entity Too Large ',
414: 'request-URI Too Large ',
415: 'unororted Media type ',
416: 'requested Range Not satisfiable ',
417: 'pectation failed ',
418: 'I \'m a teapot', // RFC 2324
422: 'unprocessable Entity ', // RFC 4918
423: 'locked', // RFC 4918
424: 'failed', // RFC 4918
425: 'unordered collect', // RFC 4918
426: 'Upgrade required', // RFC 2817
500: 'internal Server error ',
501: 'Not implemented ',
502: 'Bad Gateway ',
503: 'Service unavailable ',
504: 'Gateway Time-out ',
505: 'http Version not supported orted ',
506: 'variant Also Negotiates ', // RFC 2295
507: 'Insufficient storage', // RFC 4918
509: 'Bandwidth Limit exceeded ',
510: 'Not extended' // RFC 2774

This is excerpted from line 143 of Nodejs source code "http. js.

In fact, it is not difficult to see from the client response results:

(Lines 6): "response. end" ------ this method sends signals to the server when all response headers and packets are sent completely. The server will think the message is complete.

This method must be called after each response is complete. If the parameter "data" is specified, it is equivalent to calling "response. write (data, encoding)" and then calling "response. end ()".

(8 rows): "server. listen (8888)" ------ the server accepts the connection with the specified handle and binds it to a specific port.

The above is a detailed analysis process, hoping to help deepen understanding. although there are not many codes, it focuses on understanding some detailed mechanisms to efficiently develop NodeJS applications in the future.

III. instances

In addition to using the "request" object to access request header data, the "request" object can also be used as a read-only data stream to access request body data.

This is an example of a "POST" request:

The code is as follows:

Http. createServer (function (request, response ){
Var body = [];
Console. log (request. method );
Console. log (request. headers );
Request. on ('data', function (chunk ){
Body. push (chunk );
Request. on ('end', function (){
Body = Buffer. concat (body );
Console. log (body. toString ());
}). Listen (8888 );

The following is a complete "Http" request data content.

The code is as follows:

User-Agent: curl/7.26.0
Host: localhost
Accept :*/*
Content-Length: 11
Content-Type: application/x-www-form-urlencoded
Hello World

IV. Summary

(1) understand the concept of "Http.
(2) skilled in using Http-related APIs.
(3) pay attention to the control of details, such as the handling details between "POST and GET.
(4), "requestListener.
(5) emphasize the concept that an http request object is a readable stream, while an http response object is a writable stream.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.