node.js第11课(HTTPclient)

时间:2023-03-10 04:28:21
node.js第11课(HTTPclient)


一、http模块提供了两个函数http.request和http.get,功能是作为client向HTTPserver发起请求。

    Ext.Ajax.request({},function(response))

1.http.request(options,callback)发起HTTP请求,接受两个參数,option是一个类似关联数组的对象,

表示请求的參数,callback是请求的回调函数,option经常使用的參数例如以下

   host:请求站点的域名或IP地址

   port:请求站点的端口,默认是80,

   method:请求方法,模式是GET/POST

   path:请求的相对于根的路径,默认是"/"。QueryString应该包括在当中,比如/search?query=marico

   headers:一个关联数组对象,为请求头的内容

   callback传递一个參数,为http.ClientResponse的实例

   http.request返回一个http.ClientRequest的实例

//clientRequest.js

var http=require('http');

var querystring=require('querystring');

//启动服务

http.createServer(function(req,res){

 console.log('请求到来,解析參数');

 var post='';

 req.on('data',function(chunk){

  post+=chunk;

 });

 req.on('end',function(){

  post=querystring.parse(post);

  //解析完毕

  console.log('參数解析完毕,返回name參数');

  res.end(post.name);

 });

}).listen(3000,'127.0.0.1');

//client请求

var contents=querystring.stringify({

 nane:'octopus',

 age:20,

 address:'beijing'

});

var options={

 host:'localhost',

 path:'/',

 port:3000,

 method:'POST',

 headers:{

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

  'Content-Length':contents.length

 }

};

var req=http.request(options,function(res){

 res.setEncoding('utf-8');

 res.on('data',function(data){

  console.log('后台返回数据');

  console.log(data);

 })

});

req.write(contents);

req.end();

2.http.get(options,callback) http模块还提供了一个更加简便的方法用于处理GET请求:http.get。它是http.request的简化版,

   唯一的差别在于http.get自己主动将请求方法设为GET请求,同一时候不须要手动调用req.end();

   实例:clientGet.js

 var http=require('http');

 var url=require('url');

 var util=require('util');

//启动服务

 http.createServer(function(req,res){

   console.log('请求到来,解析參数');

   var params=url.parse(req.url,true);

   console.log('解析完毕');

   console.log(util.inspect(params));

   console.log('向client返回');

   res.end(params.query.name);

 }).listen(3000);

http.get({

   'host':'localhost',

   path:'/user?name=octopus&age=20',

   port:3000},

   function(res){

     res.setEncoding('utf-8');

     res.on('data',function(data){  

       console.log('服务端响应回来的数据为:'+data);

   })

});

二、http.ClientRequest

该对象是由http.request或http.get返回产生的对象,表示一个已经产生并且正在进行的HTTP请求,它提供了response事件,

即http。request或http.get第二个參数制定的回调函数的绑定对象,请求必须调用end方法结束请求。

提供的函数:

   request.abort() 终止正在发送的请求

   request.setTimeout(timeout,[callback]) 设置请求超时时间,timeout为毫秒数,当请求超时后,callback将会被调用

   其他:request.setNoDelay([noDelay])、request.setScoketKeepAlive([enable],[initialDelay])等函数。

   API地址:http://nodejs.org/api/http.html

三、http.ClientResponse

http.ClientReponse是与http.ServerResponse相似,提供三个事件,data、end和close,分别在数据到达,传输结束和连接结束时触发,

当中data事件传递一个參数chunk,表示接受到的数据

属性,表示请求的结果状态

    statusCode   HTTP状态码,如200,404,500

    httpVersion:HTTP协议版本号

    headers:HTTP请求头

    trailers:HTTP请求尾

函数:

response.setEncoding([encoding]):设置默认的编码,当data事件被触发时,数据将以encoding编码。默认值为null,以buffer的形式存储。

response.pause():暂停接受数据和发送事件,方便实现下载功能。

response.resume():以暂停的状态中恢复