node.js第11課(HTTPclient)

來源:互聯網
上載者:User

標籤:style   http   使用   strong   os   資料   



一、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():以暫停狀態中恢複
 
           

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.