美文网首页
001-Node 基础之 http 模块API梳理

001-Node 基础之 http 模块API梳理

作者: Node101 | 来源:发表于2017-10-26 17:13 被阅读0次

          初看Node 最新版的官方文档 看到Http模块的类以及http模块的属性和方法等,有点发懵的感觉,结合代码之后,要清晰多了,废话不多说了,接下来我顺着代码的思路将http的API 梳理下. 

1. 直接通过http 对象使用的有:重点2,3,4

1. http.STATUS_CODES

2. http.createServer(function request listener)

3. http.request(options, callback(http.IncomingMessage))

4.http.get(options, callback(http.IncomingMessage))

5 http.globalAgent


2. 作为回调参数使用的对象有:

1. http.IncomingMessage.   作为事件 ’request‘和’response‘ 的第一个参数传入

2. http.ServerResponse.      作为 ’request‘ 事件的第二个参数传入


3. 示例代码:创建服务端server对象的两种方法

varhttp = require('http');

/**

* 创建服务器的两种写法,第一种写法如下

requestListener是一个函数,会被自动添加到‘request’事件。

var server = http.createServer(function(req,res)

{ res.writeHeader(200,{'Content-Type':'text/plain'});

res.end('hello world');

});/**

/* 说明:创建服务器的第二种写法, 

通过http.Server类new一个实例对象 然后添加代码添加 request 事件

*  req 是http.IncomingMessag的一个实例, res 是http.ServerResponse的一个实例*/

var server =new http.Server();

server.on('request',function(req,res){

res.writeHeader(200,{'Content-Type':'text/plain'});

res.end('hello world');

});

由此可见,两种创建server 对象的原理是一样的,都是通过添加 ‘request’来实现. 


4. 比较http.get(options[, callback]  和  http.request(options[, callback] 方法  都是返回 http.ClientRequest对象

      因为大多数请求都是 GET 请求且不带请求主体,所以 Node.js 提供了该便捷方法。 该方法与http.request()唯一的区别是它设置请求方法为 GET 且自动调用req.end()。 注意,回调函数务必消耗掉响应数据。  callback被调用时只传入一个参数,该参数是http.IncomingMessage的一个实例。以下以http.request(options[, callback]) 使用为例 

const options={      hostname:'www.google.com',

                                 port:80,

                                path:'/upload',

                              method:'POST',

                                headers:{

                                              'Content-Type':'application/x-www-form-urlencoded',

                                               'Content-Length':Buffer.byteLength(postData)

                                  }

};

const req=http.request(options,(res)=>{  //这里的res 是http.IncomingMessage的一个实例,req是http.ClientRequest对象

            console.log(`状态码:${res.statusCode}`);

            console.log(`响应头:${JSON.stringify(res.headers)}`);

            res.setEncoding('utf8'); // http.IncomingMessage实现了stream的Readable接口

           res.on('data',(chunk)=>{console.log(`响应主体:${chunk}`);});

            res.on('end',()=>{console.log('响应中已无数据。');});});

           req.on('error',(e)=>{console.error(`请求遇到问题:${e.message}`);});

            // 写入数据到请求主体

          req.write(postData);

         req.end();


5. http 类的介绍

一共有五个类:http.Agent, http.ClientRequest,  http.Server,  http.ServerResponse ,http.IncomingMessage.

http.ClientRequest http.ServerResponse  实现了Stream的Writeable接口

http.IncomingMessage   实现了Stream的Readable接口

http.Server       继承自net.Server

相关文章

网友评论

      本文标题:001-Node 基础之 http 模块API梳理

      本文链接:https://www.haomeiwen.com/subject/zpukpxtx.html