http.request(options[,...callback])
根據(jù)Scott老師的視頻學(xué)習(xí)到了http.request()
http.request
直接貼出官方api
https://nodejs.org/api/http.html#http_http_request_options_callback
參數(shù)比較多需求的時候在查詢即可!
用Node來模擬一次評論操作
首先要拿到頭信息所以我先評論了一次然后拿到請求信息
我把cookie刪除點,大家要使用自己修改一下headers中的內(nèi)容即可
- 這個內(nèi)容以注釋的方式解釋
var http = require('http');//引入http模塊
var querystring = require('querystring');//引入querystring模塊可進行序列化
//這里是要傳入的參數(shù)用stringify的方法序列化,其效果類似于Js方法中的JSON.stringify
var postData = querystring.stringify({
'content':'老師么么噠,順便測試一下!',
'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)聽data事件,有data了觸發(fā)這個
res.on('data',function(chunk){
console.log(Buffer.isBuffer(chunk));
console.log(typeof chunk);
});
//監(jiān)聽end事件,每次觸發(fā)完都有個結(jié)束的標(biāo)志
res.on('end',function(){
console.log('評論完畢!');
});
});
//響應(yīng)失敗-觸發(fā)error事件
req.on('error',function(e){
console.log('Error: ' + e.message) ;
});
//把請求的參數(shù)寫入響應(yīng)頭
req.write(postData);
//手動執(zhí)行
//官方對這句的解釋:在實施例req.end()被調(diào)用。隨著http.request()人們必須始終調(diào)用req.end(),以表示你的要求做的-即使沒有數(shù)據(jù)被寫入請求主體。
req.end();