Node. js Lesson 10 (HTTP server)

Source: Internet
Author: User

Zookeeper

Concept: Node. js provides the http module. It encapsulates an efficient HTTP server and a simple HTTP client.
Http. server is an event-based HTTP server. It is implemented using C ++ internally. Interfaces are encapsulated by JavaScript.
Http. request is an HTTP client tool. The user sends a request to the server.
I. HTTP Server
Implemented by http. Server, it provides a set of APIs with a low encapsulation level. It is only Stream Control and simple parsing. All high-level functions must use its interfaces.
The app. js case described earlier
Code Analysis:
Http. createServer creates an http. Server instance and uses a function as an HTTP request processing function. This function accepts two parameters: the request object req and the response object's res.
Res explicitly writes the response code 200 (indicating that the request is successful), specifies the response header, and writes the response body. End is called and sent. This instance calls the listen function, starts the server, and listens to port 3000.
1. http. Server events
Http. Server is an event-based HTTP Server. All requests are encapsulated into independent events. Developers only need to write corresponding functions for their events to implement all functions of the HTTP Server,
It inherits from EventEmitter and provides the following events:
Request: when a client request arrives, this event is triggered. Two parameters, req and res, are provided, indicating the request and response information.
Connection: When a TCP connection is established, this event is triggered. A socket parameter is provided, which is an instance of net. Socket (the underlying protocol object ).
Close: this event is triggered when the server is closed.
In addition, there are checkContinue, upgrade, and clientError events.
The most common and important thing is: request events. http provides a shortcut. http. createServer ([requestListener])
Explicit implementation:
Case: server. js
Var http = require ('http ');
Var server = new http. Server ();
Server. on ('request', function (req, res ){
Res. writeHead (200, {'content-type': 'text/html '});
Res. write ('node. js ');
Res. end ('

Hello, world

');
});
Server. listen (3000 );
2. http. ServerRequest request information
This object is the most important content for backend developers. It is generally sent by the http. Server request object and is passed as the first parameter. It is usually abbreviated as request or req.
HTTP requests are divided into two parts: request header and request body ., If the request content is short, it can be read immediately after the request header is parsed. The request body may be relatively long and must be transmitted for a certain period of time. Therefore, three events are provided to control the transmission of the Request body.
(1) data: When the request body data arrives, this event is triggered. This event has a common chunk parameter, indicating the received data.
(2) end: When the request body data transmission is complete, this event is triggered and no data will arrive later.
(3) close: when the user's current request ends, this event is triggered. Unlike the end event, if the user forces to terminate the transfer, close is also triggered.
ServerReuqest attributes
Complete: whether the client request has been sent
HttpVersion: HTTP Protocol version, usually 1.0 or 1.1
Method HTTP request method, such as GET and POST
The original Request Path of the url, such as/pc/getUser or/user? Name = marico
Headers HTTP Request Header
Trailers HTTP request tail (uncommon)
Connection: the current HTTP connection Socket, which is an instance of net. Socket.
The alias of the socket connection attribute.
The alias of the client attribute.
3. GET the GET request content
Because the GET request is directly embedded in the path, the complete URL request path includes? Therefore, you can manually parse the following content as the GET parameter. The parse function in the url module of Nodejs provides this function.
Example: get. js
Var http = require ('http ');
Var urls = require ('url ');
Var util = require ('til ');

Http. createServer (function (req, res ){
Res. writeHead (200, {'content-type': 'text/plain '});
Res. end (util. inspect (urls. parse (req. url, true )));
}). Listen (3000 );
4. Get the POST request content
All the content of the POST request is in the Request body. http. ServerRequest does not have a request body attribute because it may be time-consuming to wait for the transmission of the Request body. For example, upload a file.
Malicious POST requests greatly consume server resources. Therefore, Nodejs does not parse the Request body. You need to do this manually when you need it.
Example: post. js
Var http = require ('http ');
Var querystring = require ('querystring ');
Var util = require ('til ');
Http. createServer (function (req, res ){
Var post = '';
// Register the data event listening function. Each time the request body data is received
Req. on ('data', function (chunk ){
Post + = chunk;
});
Req. on ('end', function (){
// Parse the string-formatted post into the real post request format
Post = querystring. parse (post );
// Return to the front-end
Res. end (util. inspect (post ));
});
}). Listen (3000 );
5. Information returned by http. ServerResponse to the client
The final result of the user is determined. It is sent by the reponse object of http. Server and passed as the second parameter. Usually response or res
There are three main functions:
Response. writeHead (statusCode, [headers]): sends a response header to the requested client.
StatusCode is the HTTP Status Code, for example, 200 is successful, and 404 is not found.
Headers is an object similar to an associated array, indicating each attribute of the response header.
Response. write (data, [encoding]) sends the corresponding content to the request client. data is a buffer or string, and encoding is encoded.
Response. end ([data], [encoding]) ends the response and notifies the user that all the messages have been sent. When all the content to be returned is sent, this function must be called once. If this function is not called, the client is always waiting

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.