7.http.request

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


根據(jù)Scott老師的視頻學(xué)習(xí)到了http.request()

官方文檔-http.request

http.request

直接貼出官方api

https://nodejs.org/api/http.html#http_http_request_options_callback

參數(shù)比較多需求的時(shí)候在查詢即可!

用Node來(lái)模擬一次評(píng)論操作

首先要拿到頭信息所以我先評(píng)論了一次然后拿到請(qǐng)求信息

我把cookie刪除點(diǎn),大家要使用自己修改一下headers中的內(nèi)容即可


  • 這個(gè)內(nèi)容以注釋的方式解釋
var http = require('http');//引入http模塊
var querystring = require('querystring');//引入querystring模塊可進(jìn)行序列化

//這里是要傳入的參數(shù)用stringify的方法序列化,其效果類似于Js方法中的JSON.stringify
var postData = querystring.stringify({
    'content':'老師么么噠,順便測(cè)試一下!',
    'mid':8837
});

//頭信息
var options = {
    hostname:'www.imooc.com',
    port:80,
    path:'/course/docomment',
    method:'POST',
    headers:{
      'Accept':'application/json, text/javascript, */*; q=0.01',
      'Accept-Encoding':'gzip, deflate',
      'Accept-Language':'zh-CN,zh;q=0.8',
      'Connection':'keep-alive',
      'Content-Length':postData.length,
      'Content-Type':'application/x-www-form-urlencoded;charset=UTF-8',
      'Cookie':'imooc_uuid=15f58ae7-2d00-4fc1-9801-1a78dde18bc2; imooc_isnew_ct=1482830692; loginstate=1; apsid=IxYWQwNTcwY2RiNDY2YWM3Z7999,1483688200,1483949602,1484013932; Hm_lpvt_f0cfcccd7b1393990c78efdeebff3968=1484034431; cvde=587441144e831-67; IMCDNS=1',
      'Host':'www.imooc.com',
      'Origin':'http://www.imooc.com',
      'Referer':'http://www.imooc.com/video/8837',
      'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36',
      'X-Requested-With':'XMLHttpRequest'
    }
};
    
    //調(diào)用該方法,回調(diào)由于Node是以事件流的形式往下走的,
  var req = http.request(options,function(res){
      console.log('Status: ' + res.statusCode);
      console.log('headers: ' + JSON.stringify(res.headers));
        
      //監(jiān)聽(tīng)data事件,有data了觸發(fā)這個(gè)
      res.on('data',function(chunk){
          console.log(Buffer.isBuffer(chunk));
          console.log(typeof chunk);
      });
      
      //監(jiān)聽(tīng)end事件,每次觸發(fā)完都有個(gè)結(jié)束的標(biāo)志
      res.on('end',function(){
          console.log('評(píng)論完畢!');
      });
  });

    //響應(yīng)失敗-觸發(fā)error事件
  req.on('error',function(e){
      console.log('Error: ' + e.message)   ;
  });
    
  //把請(qǐng)求的參數(shù)寫(xiě)入響應(yīng)頭
  req.write(postData);

  //手動(dòng)執(zhí)行
  //官方對(duì)這句的解釋:在實(shí)施例req.end()被調(diào)用。隨著http.request()人們必須始終調(diào)用req.end(),以表示你的要求做的-即使沒(méi)有數(shù)據(jù)被寫(xiě)入請(qǐng)求主體。
  req.end();

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容