HTTP Module for Nodejs

Source: Internet
Author: User

One, HTTP server
We know that the traditional HTTP server is Aphche, Nginx, IIS and other software to build, but nodejs do not need, Nodejs provides an HTTP module, itself can be used to build the server, for example:

var http = require ("http"); http.createserver(function(req,res) {    Res.writehead ( {        "Content-type": "Text/plain"    });    Res.write ("Hello NodeJs");    Res.end ();}). Listen (3000);

An HTTP server and an easy HTTP client are encapsulated in the HTTP module: Http.server () is used to create an event-based HTTP server, while Http.request () and Http.get () You can initiate a request to the HTTP server as a client. The Createserver () method used here returns an HTTP. The server object, Text/plain, means that the file is formatted as plain text, and the browser does not process the file when it is acquired, and if Content-type is set to text/html, The browser automatically calls the HTML parser to process the file when it obtains the file. Alternatively, you can also use new HTTP. The Server () constructor method creates http. Server objects, such as:

var http = require ("http"); var New http. Server (); Server.on ("request",function(req,res) {    ...}). Listen (3000);

The above code is created by directly creating an HTTP. Server object, and then adds a request event listener for it. HTTP created using the Createserver () method. The server object adds a request event listener by default, but it is omitted.
It says HTTP. The server event, HTTP. The most common event for server is "request", which is triggered when an HTTP request is received. In the "Request" event, the parameters req and res that passed in the callback function are HTTP respectively. Examples of incomingmessage and http.serverresponse:

http. The Incomingmessage class contains HTTP request information sent from the client, which can be used to access the response status, message headers, and data, for example:
*headers/<object>-Object of the request header or response header
*httpversion/<string>-HTTP protocol version with possible values of "1.1" or "1.0"
*method/<string>-Method of the request, such as "GET", "POST", etc.
*statuscode/<number>-HTTP response status code
*statusmessage/<string>-HTTP response status message
*url/<string>-the URL of the client sending the HTTP request

http. The Serverresponse class is the information returned to the client, which has three important methods for returning the response header, the response content, and the end request:
Writehead (statuscode[, statusmessage][,headers]): Sends a response header to the requesting client, which is called at most once in a request and, if not called,
Automatically generate a response header
Write (Chunk[,encoding][,callback]): Sends the response content to the requesting client, chunk is a buffer or a string, if chunk is a string, you need to specify the
The default is Utf-8, which can be called multiple times before the end () method call
End ([Data][,encoding][,callback]): End the response, telling the client that all sends have ended, and that if this function is not called, the client will remain in the waiting state

Other http. Events for the server class can refer to the official documentation: http://nodejs.cn/api/http.html

Second, the HTTP client

The HTTP module provides http.request () and Http.get () two methods, which function as a client to initiate a request to an HTTP server.

Http.request (Options[,callback]) method
The Http.request () method returns an HTTP. An instance of Clientrequest. Where options is an object that represents the requested parameter. Including:
*protocol/<string>-protocol used, default to HTTP
*host/<string>-the domain name or IP address of the server to which the request was sent, default to "localhost"
*hostname/<string>-alias of host
*port/<number>-port number of the remote server, default is 80
*method/<string>-Specifies the HTTP request method, which defaults to "GET"
*path/<string>-The path to the root is requested, and the default is "/", where the querystring should be included. Example:/index.html?page=12
*headers/<object>-Object containing the request header
*timeout/<number>-It sets the time-out for the socket to wait for a connection

For example:

varHTTP = require ("http");varQueryString = Require ("querystring");varPostData =querystring.stringify ({"Content": "Test",    "Mid": 8837});varOptions ={hostname:"Www.imooc.com", Port:80, Path:"/course/document", Method:"POST", headers:{"Accept": "Application/json, Text/javascript, */*; q=0.01 ",        "Accept-encoding": "Gzip, deflate",        "Accept-language": "zh-cn,zh;q=0.8",        "Connection": "Keep-alive",        "Content-length":p Ostdata.length,"Content-type": "application/x-www-form-urlencoded; Charset=utf-8 ",        "Cookie": "",        "Host": "Www.imooc.com",        "Origin": "Http://www.imooc.com",        "Referer": "http://www.imooc.com/video/8837",        "User-agent": "mozilla/5.0 (Windows NT 10.0; WOW64) applewebkit/537.36 (khtml, like Gecko) chrome/53.0.2763.0 safari/537.36 ",        "X-requested-with": "XMLHttpRequest",    }}varreq = http.request (options,function(res) {Res.on ("Data",function(Chunk) {console.log (chunk);    }); Res.on ("End",function() {Console.log (Finished ");    }); Console.log (Res.statuscode);}); Req.on ("Error",function(Err) {console.log (err.message);}) Req.write (postdata); Req.end ();

If any errors are encountered during the request, an "error" event is triggered in the returned Request object;
Using Http.request () must always call Req.end () to indicate the end of the request, even if no data is written to the principal

Http.get (Options[,callback]) method
The Http.get () method is a simplified version of the Http.request () method, and the main difference is that Http.get () automatically sets the request method to a "get" request without requiring a manual call to Req.end ()

HTTP Module for Nodejs

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.