Nodejs the HTTP module for learning notes _node.js

Source: Internet
Author: User
Tags readable rfc socket node server

First, the opening analysis

First of all, 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 same, the idea is the same,

Nodejs as a host to run the environment, JavaScript as the host language, it also has its own set of standards, this article we will come together to learn the "HTTP module." But as a prerequisite,

I hope you can read the official website provided by the API, there is a predecessor to understand, so much more convenient, the following is the HTTP part of the API overview:

Copy Code code as follows:



HTTP


http. Status_codes


Http.createserver ([Requestlistener])


Http.createclient ([Port], [host])


Class:http. Server


Events: ' Request '


Event: ' Connection '


Events: ' 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


Events: ' 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


Events: ' 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 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 ...");

(node Server.js) The following are the results of the operation:

Second, detail analysis examples

Take a specific look at this small example:

(1 lines): "Require" introduces the Nodejs "HTTP" module and assigns it to the HTTP variable.

(2 rows): Invoke 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 listener queue for the "request" event.

When a request arrives, Event-loop puts the listener callback function into the execution queue, where all the code in node is executed from the execution queue.

These executions are on the worker thread (the Event loop itself can assume that in a separate thread we generally do not mention this thread, and that node is called a single-threaded execution Environment),

All callbacks are run on a single worker thread.

We're going to look at the callback function "Requestlistener", which provides two parameters (Request,response),

Triggered each time a request is received. Note that each connection may have multiple requests (in a 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.

A "Incomingmessage" object is made up of HTTP. Created by server or http.clientrequest,

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

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

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

(3 lines): "Writeheader", using the "response.writehead ()" function to send a content type (content-type) of HTTP status 200 and HTTP headers.

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

Give me a chestnut:

Copy 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 that 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 encodings.

What needs to be further explained is that node does not check whether the Content-lenth property matches the transmitted body length.

StatusCode is a three-bit HTTP status code, for example: "404". Here is the word "http." Status_codes ", a collection of all standard" Http "response status codes and a short description are in it.

The following is the source reference:

Copy Code code as follows:



var status_codes = exports. Status_codes = {


M: ' Continue ',


' Switching protocols ',


102: ' Processing ',//RFC 2518, obsoleted by RFC 4918


: ' OK ',


201: ' Created ',


Accepted: ' The '


203: ' Non-authoritative information ',


204: ' No Content ',


205: ' Reset Content ',


206: ' Partial Content ',


207: ' Multi-Status ',//RFC 4918


' Multiple choices ',


Moved: ' Permanently ',


302: ' Moved temporarily ',


303: ' The other ',


304: ' Not Modified ',


305: ' Use Proxy ',


307: ' Temporary Redirect ',


' Bad Request ',


401: ' Unauthorized ',


402: ' Payment Required ',


403: ' Forbidden ',


404: ' Not Found ',


405: ' 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 code "http.js" 143 lines begin.

In fact, from the client answer results are not difficult to see:

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

This method must be called after each response completes. If the parameter "data" is specified, it is equivalent to invoking "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, hope to help deepen understanding, although the code is not much, but the emphasis is on understanding some details of the mechanism, so that the future efficient development of NODEJS applications.

Third, the example

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

This is an example of a "POST" request:

Copy 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 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, sum up

(1), understand the "Http" concept.
(2) Proficiency in the 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.

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.