Node Getting Started Tutorial (12) Chapter Tenth: node's HTTP Module

Source: Internet
Author: User

Ryan Dahl Development Node was originally designed to Nginx combine the non-blocking IO functionality with a highly encapsulated Web server. So node's original purpose is to be a high-performance Web server, so: node's HTTP module is also the core of the core.

This article requires you to understand the pre-knowledge points:

    • HTTP protocol
    • Web request model: request → process → response
    • Stream, event for node
Client for HTTP Module

Modules are required to use the HTTP server with the client require(‘http‘) . The HTTP module provides two functions http.request() and a http.get() helper program to send requests to the server side.

We can http.request () create a class instance that sends the request by means of the method, http.ClientRequest and after the request is created, the request is not sent immediately, and we can continue to access the request header: setHeader(name, value) , getHeader(name) and removeHeader(name) the API to modify it. The actual request header is sent with the first block of data or when it request.end() is called.

http. Clientrequest class
    • http.ClientRequestClass inherits EventEmitter , it internally defines the following events.
Events Description
Abort is triggered when the request has been terminated by the client. This event is only triggered when abort () is first called.
connect

Is triggered whenever the server responds to a connect request.

If the event is not being monitored, the client that receives the Connect method closes the connection.

continue

Triggers when the server sends an HTTP response of continue,

Usually because the request contains Expect:100-conti Nue

This is the instruction that the client will send the request principal.

response

Triggers when the requested response is received.

This event is triggered only once. If the ' response ' event handler is not added, the response is discarded entirely.

If you add the ' response ' event handler, you must consume the data of the response object, and

can either call Response.read (), or add a ' data ' event handler,

, or call the. Resume () method. The ' End ' event is triggered when the data is exhausted. The

Consumes memory before the data is read and may cause a ' process out of memory ' error.

socket triggers when the socket is assigned to a request.
timeout

Triggered when the underlying socket timed out.

This method notifies only the idle socket. The request must be stopped manually.

upgrade

is triggered whenever the server responds to a upgrade request.

If the event is not being monitored, the client that receives the upgrade request header closes the connection.

    • http.ClientRequestClass also provides methods for handling requests and returning responses.
Method Parameters Description
request.end([data[, encoding]][, callback]) data sent data ② encoding encoded ③callback callback function Ends the send request. If some of the request principals have not yet been sent, they are flushed to the stream. If the request is chunked, the terminating character ' 0\r\n\r\n ' is sent. If data is specified, it is equivalent to calling Request.write (data, encoding) before calling Request.end (callback). If callback is specified, it is called when the request flow ends.
request.flushHeaders() No Refreshes the request header. For efficiency reasons, node. JS typically caches the request header until Request.end () is called or the first request data is written. node. js then packages the request header and data into a single TCP packet.
request.getHeader(name) ①name② return string read out the request header, note: The parameter name is case-sensitive
request.removeHeader(name) Name string Remove a header already in the Headers object.
request.setHeader(name, value) ①name is the key②value of the header. Sets a single header value for the Headers object. If the header already exists, it will be replaced. Here, a string array is used to set multiple headers with the same name.
request.setSocketKeepAlive([enable][, initialDelay]) ①enable type Boolean②initialdelay Once the socket is assigned to the request and connected, socket.setkeepalive () is called.
request.setTimeout(timeout[, callback]) The number of milliseconds that the ①timeout request is considered to be timed out. ②callback an optional function that is called when a time-out occurs. is equivalent to binding to a timeout event. Once the socket is assigned to the request and connected, Socket.settimeout () is called.
request.write(chunk[, encoding][, callback]) The request data sent by the ①chunk. ②encoding: encoding; ③callback callback function A block of data that sends the request body. By calling this method multiple times, a request principal can be sent to a server, in which case, the request header is recommended using [' transfer-encoding ', ' chunked '] when creating the request.
Send a GET request
Introducing the HTTP ModuleConst HTTP =Require' http ');Create a requestLet request = Http.request ({Protocol' http: ',The requested protocol host:' Aicoder.com ',Requested host Port: //Port method: ' get ',// GET Request Timeout: $ , //Timeout time path: '/'// Request Path}, res = { //After the connection succeeds, the callback function is called once the response returned by the backend server is received. //Res = http. Incomingmessage: is a readable Stream res.on (' data ', data = { Console.log (data.tostring (' UTF8 ')); //print the returned data. }); }); //Set Request header Request.setheader (' Cache-control ', ' max-age=0 ');  True send request Request.end ();                 
Another way to send a GET request

The HTTP module also provides a simpler version of the request to handle the Get method, and the http.get(options,callback) only difference is that Http.get automatically sets the http.request() request method to a GET request without having to manually call Req.end ();

http.get(‘http://aicoder.com‘, res => {  res.on(‘data‘, data => {    console.log(data.toString(‘utf8‘));  });});
Send a POST request

And see an example of sending a POST request.

const http = require ( ' http '); Span class= "Hljs-keyword" >let request = Http.request ({protocol:  http: ', host:  ' aicoder.com ', port: 80, method:  ' POST ', timeout: 2000, path: console.log (data.tostring ( ' UTF8 ')); }); //send the requested data. Request.write (      
HTTP Server-side

http.ServerA simple Web server is implemented and the request and response are also encapsulated.

Events for Http.server objects

http.serveris an event-based HTTP server, all requests are encapsulated into separate events, we only need to write the corresponding number of rows of his event to implement all the functions of the HTTP server, it inherits from Eventemitter, provides the following events:

    1. request: When the client request arrives, the event is triggered, providing two parameter requests and response, respectively, HTTP. Serverrequest and Http.serverresponse represent the request and the response information.
    2. connection: When TCP establishes a connection, the event is triggered, providing a parameter socket for the Net.socket instance (underlying protocol object)
    3. close: Will be triggered when the server shuts down
    4. In addition, there are checkContinue , and upgrade clientError other events

What we use most is the request event, and HTTP also provides a shortcut to the event:http.createServer([requestListener])
Let's take a brief look at two cases:

The first one: Use the request event:

Const HTTP =Require' http ');Let Server =New HTTP. Server (); Server.on (console.log (Req.url); //Set the answer header information Res.writehead (200, { ' Content-Type ' :  text/html '}); Res.write ( ' Hello we are family<br> '); Res.end ( "server Already end\n ');}); //showed three times this also proves TCP's three-time handshake Server.on ( ' connection ', () = {console.log ( ' handshake ');}); Server.on ( ' close ', () = {console.log ( ' server would close ');}); //shutdown service in order to trigger the Close event server.close (); Server.listen (8080);   

Second: Take advantage of http.createServer creating server instance code:

const http = require(‘http‘);http.createServer(function(req,res){ res.writeHead(200,{‘Content-Type‘:‘text/plain‘}) res.write("hi, from aicoder.com"); res.end();}).listen(3000);
http. Serverrequset Request Information

We all know that the HTTP request is divided into two parts: the request header and the request body, if the content of the request is directly after the request header protocol is completed immediately read, the request body may be relatively longer, need some time transmission. Therefore, three events are provided to control the transfer of the request body.

1. data : When the request body data arrives, the event is triggered, the event is a total of one parameter chunk, indicating the data received.
1. end : When the request body data transfer is complete, the event is triggered and there will be no more data coming.
1. close : At the end of the user's current request, the event is triggered, unlike end, which triggers close if the user forces the transfer to terminate

Properties of the Serverrequest

name meaning
Ccomplete Whether the client request has been sent to completion
Httpversion HTTP protocol version, usually 1.0 or 1.1
Method HTTP request methods, such as: Get,post
Url The original request path
Headers HTTP request Header
Trailers HTTP request tail (uncommon)
Connection The current HTTP connection socket, which is net. Instance of socket
Socket Alias of the Connection property
Client Alias for client Property
http.createServer(function(req,res){    console.log(req.httpVersion);    //console.log(req.socket); console.log(req.headers); console.log(req.method); res.writeHead(404,{‘Content-Type‘:‘text/plain‘}) res.write("we are is content"); res.end();}).listen(8080);
Get the GET Request content

Since the GET request is directly embedded in the path, the URL is the complete request path, including the following section, so you can manually parse the following content as a get parameter, and the parse function in the Nodejs URL module provides this functionality.

const http = require(‘http‘);const url = require(‘url‘);const util = require(‘util‘);http .createServer((req, res) => { //利用url模块去解析客户端发送过来的URL res.write(util.inspect(url.parse(req.url, true))); res.end(); }) .listen(8080);
Get POST Request Content

The contents of the POST request are all in the request body, http. Serverrequest does not have a property content of the request body, because waiting for a request body transfer can be a time-consuming task. such as uploading files. A malicious post request can greatly consume the resources of the server. So Nodejs is not parsing the request body, you need to do it manually when you need it.

Simply look at the code:

//get POST request data  Const HTTP = require ( ' http ');  Const UTIL = require ( ' util '); require ( ' querystring '); http. Createserver ( (req, res) = = { Let post = 60004);            
http. Serverresponse Returning Client Information

http.ServerResponseThis class implements (rather than inherits from) a writable stream interface. Inherited it EventEmitter . It is used to send a response result to the user, it is http.Server sent by the request event, and is passed as the second parameter. Generally response or res
The main three functions:

    • response.writeHead(statusCode,[headers]): Sends a response header to the requesting client.
      • statusCodeis the HTTP status code, such as 200 for success, 404 Not Found etc.
      • headersis an object that resembles an associative array that represents each property of the response header.
    • response.write(data,[encoding])Send the appropriate content to the requesting client, data is buffer or string, encoding is encoded
    • response.end([data],[encoding])End the response, informing the user that all the send has completed, when all the content to be returned is sent, the function must be called once, and if not called, the client is always in a wait state
Summarize

The real development environment, do not use such a low-level API to do Web site or micro-service, generally choose KOA or express frame. However, you can also feel the joy of the development of node native through the underlying API.

Reference:

1.51357464
1.http://nodejs.cn/api/http.html#http_http_createserver_requestlistener

Old horse free Video tutorial

Back to Tutorial list home

GitHub Address: Https://github.com/malun666/aicoder_node

Node Getting Started Tutorial (12) Chapter Tenth: node's HTTP Module

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.