"Nodejs Learning" 2. Network-related

Source: Internet
Author: User

1. A small example of official documentation

HTTP is a built-in module

var http = require (' http ');

Http.createserver (function (request, response) {

Response.writehead ($, {' Content-type ': ' Text-plain '});

Response.End (' Hello world\n ');

}). Listen (8124);

. createserver create server,. Listen method Listener Port

An HTTP request is a data stream consisting of a request header and a request body.

POST / HTTP/1.1User-Agent: curl/7.26.0Host: localhostAccept: */*Content-Length: 11Content-Type: application/x-www-form-urlencodedHello World

2. Request to send parsing data

When the HTTP request is sent to the server, it can be sent as a data stream in one byte from the beginning to the end, and the HTTP server created by the HTTP module calls back the callback function after it receives the complete request header, in the callback function, The request object can be accessed as a read-only data stream to access the data of the specific request body, in addition to the requester object's ability to access the header data.

var http = require (' http ');
Http.createserver (function (request, response) {
    var body = [];
    Console.log (Request.method);
    Console.log (request.headers);
    request.on (' Data ', function (chunk) {
        Body.push (chunk+ ' \ n ');   
   });   
    Response.on (' End ', function () {       
         BODY = buffer.concat (body);       
         Console.log (body.tostring ());   
   });
}). Listen (3001);

Response writing request header data and Entity data

var http = require (' http ');
Http.createserver (function (request, response) {
Response.writehead ($, {' Content-type ': ' Text/plain '});

Request.on (' Data ', function (chunk) {
Response.Write (chunk);
});

Request.on (' End ', function () {
Response.End ();
});
}). Listen (3001);

3. Client mode:

var http = require (' http ');
var options = {
Hostname: ' Www.renyuzhuo.win ',
PORT:80,
Path: '/',
Method: ' POST ',
headers:{
' Content-type ': ' application/x-www-form-urlencoded '
}
};

var request = http.request (options, function (response) {
Console.log (response.headers);
});

Request.write (' Hello ');
Request.end ();

Get handy notation

Http.get (' Http://www.renyuzhuo.win ', function (response) {});

Response as a read-only data stream to access

var http = require (' http ');
var options = {
Hostname: ' Www.renyuzhuo.win ',
PORT:80,
Path: '/',
Method: ' GET ',
headers:{
' Content-type ': ' application/x-www-form-urlencoded '
}
};
var body=[];
var request = http.request (options, function (response) {
Console.log (Response.statuscode);
Console.log (response.headers);

Response.on (' Data ', function (chunk) {
Body.push (chunk);
});

Response.on (' End ', function () {
BODY = Buffer.concat (body);
Console.log (Body.tostring ());
});

});

Request.write (' Hello ');
Request.end ();

Https:https requires additional SSL certificates

var options = {
Key:fs.readFileSync ('./ssl/dafault.key '),
Cert:fs.readFileSync ('./ssl/default.cer ')
}
var server = https.createserver (options, function (request, response) {});

SNI technology that dynamically uses different certificates depending on the domain name used by the HTTPS client request

Server.addcontext (' foo.com ', {
Key:fs.readFileSync ('./ssl/foo.com.key '),
Cert:fs.readFileSync ('./ssl/foo.com.cer ')
});

Server.addcontext (' bar.com ', {
Key:fs.readFileSync ('./ssl/bar.com.key '),
Cert:fs.readFileSync ('./ssl/bar.com.cer ')
});

HTTPS client requests almost the same

var options = {
Hostname: ' www.example.com ',
port:443,
Path: '/',
Method: ' GET '
};
var request = https.request (options, function (response) {});
Request.end ();

4.URL

http://User:pass @ host.com:8080/p/a/t/h? query=string #hash
-----      ---------          --------         ----   --------     -------------       -----
Protocol auth hostname Port Pathname Search Hash

The. Parse method converts a URL string into an object

Url.parse ("http://User:pass @ host.com:8080/p/a/t/h query=string #hash);

/*

Url
{
Protocol: ' http: ',
Slashes:null,
Auth:null,
Host:null,
Port:null,
Hostname:null,
Hash: ' #hash ',
Search: '? query=string%20 ',
Query: ' query=string%20 ',
Pathname: '%20//%20user:pass%[email protected]%20host.com%20:%208080%20/p/a/t/h%20 ',
Path: ‘/p/a/t/h?query=string‘ ,
HREF: ' Http://user:[email protected]:8080/p/a/t/h?query=string#hash '
}

*/

. Parse also supports the second third parameter, the second parameter equals True, the returned URL object is no longer a string, but a querystring template after the conversion of the Parameter object, the third parameter equals True, you can parse the URL without the protocol header such as:/ /www.example.com/foo/bar

The. Resolve method can be used for stitching URLs.

5.Query String

The URL parameter string is converted to and from the Parameter object.

Querystring.parse (' Foo=bar&baz=qux&baz=quux&corge ');

/*=>

{foo: ' bar ', baz:[' qux ', ' Quux '],coge: '}

*/

Querystring.stringify ({foo: ' bar ', baz:[' qux ', ' Quux '],corge: '});

/*=>

' Foo=bar&baz=qux&baz=quux&corge '

*/

6.Zlib

Data compression and decompression functions. If the client supports gzip, it can be returned using the Zlib module.

Http.createserver (function (request, response) {
var i = 1024x768, data = ';

while (i--) {
Data + = '. ';
}

if (request.headers[' accept-eccoding ']| | '). IndexOf (' gzip ')!=-1) {
Zlib.gzip (data, function (err, data) {
Response.writehead (200, {
' Content-type ': ' Text/plain ',
' content-encoding ': ' gzip '
});
Response.End (data);
});
}else{
Response.writehead (200, {
' Content-type ': ' Text/plain '
});
Response.End (data);
}

}). Listen (3001);

Determine if the service side supports gzip compression and, if supported, extract the corresponding body data using the Zlib module.

var options = {
Hostname: ' www.example.com ',
PORT:80,
Path: '/',
Method: ' GET ',
headers:{
' accept-encoding ': ' Gzip,deflate '
}
};

Http.request (options, function (response) {
var body = [];

Response.on (' Data ', function (chunk) {
Body.push (chunk);
});

Response.on (' End ', function () {
BODY = Buffer.concat (body);

if (response.headers[] = = = ' gzip ') {
Zlib.gunzip (body, function (err, data) {
Console.log (Data.tostring ());
});
}else{
Console.log (Data.tostring ());
}

});

});

7.Net

NET can create a socket server with a socket client. To implement HTTP requests and corresponding from the socket plane:

//server-side

Net.createserver (function (conn) {
    conn.on (' Data ', function (data ) {
        conn.write ([
             ' http/1.1 OK ',
            ' Content-type:text/plain ',
            ' Content-length:11 '
            ',
             ' Hello world '
        ].join (' \ n '));
   });
}). Listen (+);

Client
var options = {
PORT:80,
Host: ' www.example.com '
};

var clien = net.connect (options, function () {
Clien.write ([
' get/http/1.1 ',
' user-agent:curl/7.26.0 ',
' Host:www.baidu.com ',
' Accept: */* ',
‘‘,
‘‘
].join (' \ n '));
});
Clien.on (' Data ', function (data) {
Console.log (Data.tostring ());
Client.end ();
});

"Nodejs Learning" 2. Network-related

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.