Nodejs the HTTP module for learning notes

Source: Internet
Author: User
Tags rfc node server

First, the opening analysis

First, the concept of "Http" should be more familiar, it is not based on a specific language, is a general application layer protocol, different languages have different implementation details, but original aim, the idea is the same,

Nodejs as a hosting environment, JavaScript is the host language, it also has its own set of standards to implement, this article we come together to learn about the "HTTP module." But as a precondition,

I hope you can read the official website to provide the API, there is a pre-understanding, so much more convenient, the following is the HTTP part of the API overview:

Copy the code 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: ' Clienterror '
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: ' Continue '
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, create a file called Server.js, and write the following code:

Copy the code 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 ...");

The following is the result of the operation (node Server.js):

Second, the detailed analysis example

Take a look at this small example:

(1 lines): Introduce the "HTTP" module from the Nodejs with "require" and assign it to the HTTP variable.

(2 rows): Invokes the function provided by the HTTP module: "Createserver". This function returns a new Web server object.

The parameter "Requestlistener" is a function that will automatically be added to the listening queue for the "request" event.

When a request arrives, Event-loop will put the listener callback function in the execution queue, and all the code in node is executed from the execution queue.

These executions are on the worker thread (the Event loop itself can be thought of as a separate thread, we don't generally mention this thread, and node is called a single-threaded execution Environment),

All callbacks are run on a worker thread.

Let's take a look at the callback function "Requestlistener", which provides two parameters (Request,response),

Triggered each time a request is received. Note that there may be multiple requests for each connection (in Keep-alive connection).

"Request" is HTTP. An instance of Incomingmessage. "Response" is HTTP. An instance of Serverresponse.

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

An "Incomingmessage" object is made up of HTTP. Created by 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 state of the answer, header files and data.

It implements the "Stream" interface along with the following additional events, methods, and properties. (Specific reference API).

(3 lines): "Writeheader", using the "response.writehead ()" function to send an HTTP status 200 and an HTTP header content type (Content-type).

Reply to the response header to the request. "StatusCode" is a three-bit HTTP status code, for example 404. The last parameter, "headers", is the content of the response header.

Give me a chestnut:

Copy the code code as follows:
var body = ' Hello world ';
Response.writehead (200, {
' Content-length ': body.length,
' Content-type ': ' Text/plain '
}) ;

Note: The content-length is computed in bytes (byte), not in characters (character).

The previous example is because the string "Hello world!" contains only single-byte characters.

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

It should be further explained that node does not check whether the Content-lenth property and the transferred body length match.

StatusCode is a three-bit HTTP status code, for example: "404". The point here is "http." Status_codes ", the set of all standard" Http "response status codes and a short description are all inside.

The following is the source code reference:

Copy the code code as follows:
var status_codes = exports. Status_codes = {
: ' Continue ',
101: ' Switching Protocols ',
102: ' Processing ',//RFC 2518, obsoleted by RFC 4918
: ' OK ',
201: ' Created ',
202: ' Accepted ',
203: ' Non-authoritative information ',
204: ' No Content ',
205: ' Reset Content ',
206: ' Partial Content ',
207: ' Multi-Status ',//RFC 4918
: ' Multiple Choices ',
301: ' Moved permanently ',
302: ' Moved temporarily ',
303: ' See other ',
304: ' Not Modified ',
305: ' Use Proxy ',
307: ' Temporary Redirect ',
: ' 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 time-out ',
409: ' Conflict ',
410: ' Gone ',
411: ' Length Required ',
412: ' Precondition Failed ',
413: ' Request Entity Too Large ',
414: ' Request-uri Too Large ',
415: ' Unsupported Media Type ',
416: ' Requested Range not satisfiable ',
417: ' Expectation Failed ',
418: ' I\ ' m a teapot ',//RFC 2324
422: ' Unprocessable Entity ',//RFC 4918
423: ' Locked ',//RFC 4918
424: ' Failed Dependency ',//RFC 4918
425: ' Unordered Collection ',//RFC 4918
426: ' Upgrade Required ',//RFC 2817
$: ' Internal Server Error ',
501: ' Not implemented ',
502: ' Bad Gateway ',
503: ' Service unavailable ',
504: ' Gateway time-out ',
505: ' HTTP Version not supported ',
506: ' Variant Also negotiates ',//RFC 2295
507: ' Insufficient Storage ',//RFC 4918
509: ' Bandwidth Limit exceeded ',
510: ' Not Extended '//RFC 2774
};

Excerpt from, Nodejs source "Http.js" 143 lines start.

In fact, from the client to answer the result is not difficult to see:

(6 lines): "Response.End"------This method sends the signal to the server when all the response headers and messages are sent. The server will think the message is complete.

The method must be called after each response is completed. If the parameter "data" is specified, it is equivalent to calling "Response.Write (data, encoding)" Before calling "Response.End ()".

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

The above is a more detailed analysis process, hoping to help deepen understanding, although the code is not much, but to understand some of the details of the mechanism, in order to efficiently develop NODEJS applications in the future.

Third, examples

In addition to accessing the request header data using the "Request" object, the request object can also be accessed as a read-only stream of data.

Here is an example of a "POST" request:

Copy the code 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 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

Four, summarize

(1), understand the "Http" concept.
(2), skilled use of "Http" related APIs.
(3), pay attention to the details of the control, such as: "Post,get" between the processing details.
(4), "Requestlistener" understanding.
(5), emphasizing a concept: an HTTP Request object is a readable stream, while an HTTP response object is a writable stream.

Nodejs the HTTP module for learning notes

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.