node.js学习笔记之http模块

本文基于Node.js v6.9.4,详情请参考官网API

1. 创建服务器http.createServer

方式一和方式二效果一样,方式一只不过是在创建服务器时,自动绑定了'request'事件

// 方式一 http.createServer([requestListener])
/*
 * [requestListener(req, res)] 用户请求后回调函数,有两个参数,req请求;res响应
 * @return http.Server 返回一个http.Server实例
 */
var server = http.createServer((req, res) => {
    res.writeHeader(200,{'Content-Type':'text/plain'});
    res.end('hello world');
})

 // 方式二 new http.Server()
 var server = new http.Server();
 server.on('request', (req, res){
    res.writeHeader(200,{'Content-Type':'text/plain'});
        res.end('hello world');
 })

2. http.Server

上例中的server就是http.Server的一个实例
此模块会触发以下事件

  • checkContinue 当请求头Expect的值是 100-continue时触发
  • checkExpectation 当请求头Expect的值不是 100-continue时触发
  • clientError 客户端触发了一个error错误
    function(exception){}
  • close 关闭服务器时触发
function(errno){}
  • connect 如果客户端发起connect请求时触发
// 当一个新的TCP stream建立后发送此消息,stream是一个net.Stream的对象,通常用户不会访问/使用这个事件
function(stream){}
  • connection 新的TCP流建立时触发
  • request 客户端请求事件
/*
 * req是http.ServerRequest的一个实例,
 * res是http.ServerResponse的一个实例
 */
function(req, res){}
  • upgrade 每当一个客户端请求一个http upgrade 时候发出此消息
/*
* socket是在服务器与客户端之间连接用的网络socket
* head 是Buffer 的一个实例
*/
function(req, socket, head){}

3. http.request(options[,callback])

客户端向http服务器发起请求

/*
 * options {hostname: string, port:number, method:string, path:string, handers:{}}
 *  hostname 服务器域名或IP地址
 *  port 端口
 *  method 请求方式,有GET、POST、INPUT、DELETE、CONNECT,默认为GET
 *  path: 请求地址,可包含查询字符串及可能村长的锚点,例如'/index.html?page=12'
 *  handers: 一个包含请求头的对象
 *  @return http.ClientRequest 返回http.ClientRequest的实例
 */
 var options = {
        hostname : 'www.baidu.com',
        port : 80,
        method : 'GET',
        path : '/upload',
        handers:{
            'Connection':'keep-alive', // 通知Node此链接保持到下一次请求
            'Content-length': 1000,    // 设置请求主体字节数
            'Expect':'100-continue'
        }
 }
 var req = http.request(options, (res) => {})

4. http.get(options,callback)

http.get是http.request的简化版,唯一的区别在于http.get自动将请求方法设为了GET请求,同时不需要手动调用req.end()

var http = require('http');
http.createServer( (req, res) => {

}).listen(3000);

http.get('http://www.baidu.com/index.html', (res) => {
    console.log('get response Code:'+ res.statusCode);
}).on('error', (e) => {
    console.log('错误:'+ e.message);
})

5. http.ClientRequest

http.ClientRequest 是http.request或者http.get返回产生的对象,表示一个已经产生而且正在进行的http请求,提供一个response事件,也就是我们使用http.get和http.request方法中的回调函数所绑定的对象,我们可以显示的绑定这个事件的监听函数。

var http = require('http');

var options = {
    hostname: 'www.baidu.com',
    port:'8080'
}

// 这里的req就是http.ClientRequest的一个实例,注意与http.IncomingMessage的区别
var req = http.request(options);
req.on('response', function(res){
    res.setEncoding('utf-8');
    res.on('data', function(chunk){
        console.log(chunk.toString())
    });
    console.log(res.statusCode);
})

req.on('error', function(err){
    console.log(err.message);
});
req.end();

http.ClientRequest也提供了write和end函数,用于向服务器发送请求体,通常用于POST、PUT等操作,所有的写操作都必须调用end函数来通知服务器,否则请求无效。


作为回调参数使用的对象

6. http.ServerResponse

http.ServerResponse是服务器返回给客户端的信息,一般由http.Server的request事件发送,并作为第二个参数传递,它有三个重要的成员函数,用户返回响应头、响应内容已经结束请求。

// 这里的res就是http.ServerResponse的一个实例
http.createServer( (req, res) => {})

6.1 res.writeHead(statusCode[,headers])

向用户发送响应头,该函数在一个请求中最多调用一次,如果不调用,则自动生成一个响应头

6.2 res.write(data[,encoding])

向用户发送响应内容,data是发送的内容,encoding是编码格式

6.3 res.end(data[,encoding])

结束响应,该函数必须被调用一次

7. http.IncomingMessage

http.IncomingMessage是HTTP请求的信息,是后端开发着最关注的内容,一般由http.Serve的request事件发送,并作为第一个参数传递。

// 这里的req就是http.IncomingMessage的一个实例
var http = require('http')
http.createServer( (req, res) => {})
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容