注:此博客是在学习进击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()