1. 程式人生 > >node.js學習筆記--HTTP之request請求

node.js學習筆記--HTTP之request請求

注:此部落格是在學習進擊Node.js基礎(一)這門課程時的學習筆記,感謝Scott老師的課程。

var http = require('http')
var querystring = require('querystring')  //這個庫可以把物件序列化

var postData = querystring.stringify({
    'content':'來測試一下評論的程式碼~',
    'cid': 348
})
//content是評論內容,cid是課程視訊id, 因為慕課網上的評論裡Form Data表單裡需要傳入這兩個資料
//是在瀏覽器開發者模式下的Network欄,傳送評論後會出現請求記錄,點Header就能看到請求頭和表單的資料
//構建request需要的第一個引數 var options = { hostname:'www.imooc.com', port: 80, path:'/course/document', method: 'POST', headers: { 'Accept':'application/json, text/javascript, */*; q=0.01', 'Accept-Encoding':'gzip, deflate, br', 'Accept-Language':'zh-CN,zh;q=0.8,en;q=0.6'
, 'Connection':'keep-alive', 'Content-Length': postData.length, 'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8', 'Cookie':'imooc_uuid=96555c09-c4ba-4150-8aac-a6cd135a0c78; imooc_isnew_ct=1519916231; PHPSESSID=t95jsvcho2ic40e0k741ko4944; loginstate=1; apsid=ViMDM1MTNlMzE5MWU3NWEzZTlhYzc3MTYzMmJkYzcAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMzAwMzk5MwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABzcml0aW5nQDE2My5jb20AAAAAAAAAAAAAAAAAAAAAADI2NWYwY2JmOThlMWNiOWNiNGMyNmU1MzkyODgyN2YxIrWnWiK1p1o%3DYz; last_login_username=sriting%40163.com; IMCDNS=0; Hm_lvt_f0cfcccd7b1393990c78efdeebff3968=1519916232,1520940330; Hm_lpvt_f0cfcccd7b1393990c78efdeebff3968=1521185471; imooc_isnew=2; cvde=5aa7b5053e485-193'
, 'Host':'www.imooc.com', 'Origin':'https://www.imooc.com', 'Referer':'https://www.imooc.com/comment/348', 'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36', 'X-Requested-With':'XMLHttpRequest' } } //console.log(postData.length) var req = http.request(options, function(res){ console.log('Status: '+ res.statusCode) //列印請求的狀態碼來看請求是否成功 console.log('headers:' + JSON.stringify(res.headers)) res.on('data', function(chunk){ console.log(Buffer.isBuffer(chunk)) console.log(typeof chunk) }) //看看回復的是不是流資料 res.on('end', function(){ console.log('評論完畢!') }) }) //res是請求後的回撥函式拿到的回覆,req是請求 req.on('error', function(e){ console.log('Error: '+ e.message) }) req.write(postData) req.end()