NodeJS learning notes Http module and nodejs learning notes Module

Source: Internet
Author: User
Tags node server

NodeJS learning notes Http module and nodejs learning notes Module

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:

Copy the Code as follows:
HTTP
Http. STATUS_CODES
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:

Copy the Code 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.

Example:

Copy the Code 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:

Copy the Code as follows:
Var STATUS_CODES = exports. STATUS_CODES = {
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:

Copy the Code 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.

Copy the Code as follows:
POST, HTTP, 1.1
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.

Related Article

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: info-contact@alibabacloud.com 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.