Node. js entry-9.api: HTTP

Source: Internet
Author: User

An important task of node is to create Web Services. Next we will learn an important API related to this-HTTP. We use HTTP. createserver () to create an HTTP service instance to process requests from customers. The HTTP module contains some important content. Let's take a look at it.

HTTP Server

Let's first look at a simple example of how to create a simple server.

 
Require ('http'). createserver (Function(Req, Res ){
Res. writehead (200, {}); Res. End ('Hello World ');}
). Listen (8125 );

The aboveCodeIt is relatively simple to use require ('HTTP ') to create an HTTP instance, then use the createserver method to create a server, and use listen to port 8125. The above Code uses the chained encoding style. Although simple, the readability is poor, and the variable reusability is not good, we recommend that you use the following encoding style.

VaRHTTP = require ('http');VaRServer =HTTP. createserver ();VaRHandlereq =Function(Req, Res) {res. writehead (200, {}); Res. End ('Hello world') ;}; Server. On ('Request', Handlereq); server. Listen (8125 );

Now the code is much clearer, through var Server = http. createserver () creates a server and stores it in the variable server. Next, use server. on ('request', handlereq) binds a request event. Binding Request events. For example, the chain-style encoding is not directly reflected.

HTTP provides many other events, which are briefly described below.

1. Connection and close: Establish and close the TCP connection with the client, respectively.

2. checkcontinue: when the client sends a large amount of data to the server, it will check whether it can continue and trigger the event. When a checkcontinue event is triggered, the request event is no longer triggered.

3. Upgrade: triggered when the client requests an upgrade protocol. If the event is not handled, the server rejects the upgrade.

4. clienterror: triggered when an exception occurs on the client.

 

HTTP client

You can use HTTP. clientrequest to create an HTTP request. Let's take a look at an example:

VaRHTTP = require ('http');VaROpts ={Host:'Www .google.com'Port:80, Path:'/', Method:'Get'};VaRReq = http. Request (OPTs,Function(RES) {console. Log (RES); res. On ('Data ',Function(Data) {console. Log (data) ;}); Req. End ();

We created an HTTP request, added a data event to the response, and finally initialized and sent our request using Req. End.

Create an http get request

VaRHTTP = require ('http');VaROpts ={Host:'Www .google.com'Port:80, Path:'/',};VaRReq = http. Get (OPTs,Function(RES) {console. Log (RES); res. On ('Data ',Function(Data) {console. Log (data );});});

The difference between this example and the previous example is that the OPTs object uses the HTTP. get () replaces the previous var Req = http. request () and req. end (). Since the returned data is binary data, we need to use response. setencoding () for encoding, so we need to make minor changes to the Code.

VaRHTTP = require ('http');VaROpts ={Host:'Www .google.com'Port:80, Path:'/',};VaRReq = http. Get (OPTs,Function(RES) {console. Log (RES );
Res. setencoding ('utf8'); res. On ('Data ',Function(Data) {console. Log (data );});});

 

Use http post and put to send data

  var  Options =  {Host:  'www .example.com ', Port:  80 , path:  '/submit' , method:  'post' };   var  Req = http. request (options,  function   (RES) {res. setencoding ( 'utf8' ); Res. on ( 'data',  function   (chunk) {console. log ( 'body: '+  chunk) ;}); req. write ( "my data" ); req. write ( "more of my data" ); req. end ();  

In the above example, we use the req. Write () method to describe the data we want to send to the server, and finally use Req. End () to initialize and send a request. The res in the Code is a clientresponse object. It has two important attributes: statuscode and header ).

 

URL

The URL module provides some methods to make it easier to parse and process URL strings, including parse, format, and resolve. Let's take a look at the example. Execute the following commands in node repl line by line (the previous course described how to use node. js-8.api: events ).

 
VaRUrl = require ('url');VaRMyurl ="Http://www.nodejs.org/some/url? With = query & Param = That & are = awesome # alsoahash"; Myurlparsedurl=URL. parse (myurl); parsedurl= URL. parse (myurl,True);

Execution result:

 

Querystring

Querystring module is used to process querystring strings. It includes the following methods: parse, decode, escape, Unescape, unescapebuffer, encode, and stringify. Let's look at an example.

 
VaRQs = require ('querystring'); Qs. parse ('A = 1 & B = 2 & C = D ');

Execution result:

Next, let's look at the encode method.

 
VaRQs = require ('querystring');VaRMyobj = {'A': 1, 'B': 5, 'C': 'cats', 'function ':Function() {Console. Log ('Dogs')} Qs. encode (myobj );

Execution result:

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.