http---get/request

来源:互联网 发布:javascript ajax例子 编辑:程序博客网 时间:2024/05/17 01:29

get和request可以从后台发起一个http的请从而获取远程的资源。

使用方法:

http.request(options[,callback])


举例:向慕课网评论区写评论

var http = require('http')
var querystring = require('querystring')//可以把一个对象序列化


var postData = querystring.stringify({
'content':'一起期待下一期的课程',
'cid':348
})


var options = {
hostname:'www.imooc.com',
port:80,
path:'/course/documnet',
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=9d7f4e9c-cb3e-49a4-b485-0512c859e15f; imooc_isnew_ct=1488697529; loginstate=1; apsid=M0NDg1ZmNhZjBkMGIzYzM3ZmZlYzQyMjFjMjUyNTAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAANTI4MjkwMQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAxNzI1MjI1NDY0QHFxLmNvbQAAAAAAAAAAAAAAAAAAADU2Zjg4MzE1NzRlM2U1ZWU4YzI0OWZmNmY3MDM2YzU29K6%2FWfSuv1k%3DMW; last_login_username=1725225464%40qq.com; PHPSESSID=cp3stai5c2kgab9elmfus2djt0; IMCDNS=0; Hm_lvt_f0cfcccd7b1393990c78efdeebff3968=1506493556,1506660744,1507170233,1507283985; Hm_lpvt_f0cfcccd7b1393990c78efdeebff3968=1507291587; imooc_isnew=2; cvde=59d753f32f677-16',
        'Host':'www.imooc.com',
        'Origin':'http://www.imooc.com',
        'Referer':'http://www.imooc.com/video/8837',
        'User-Agent':'Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36',
        'X-Requested-With':'XMLHttpRequest'
}
}




var req = http.request(options,function(res){//向慕课网后台发request请求,往里写一个评论
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('评论完毕!')
})


})


req.on('error',function(e){
console.log('Error:' + e.message)
})
req.write(postData)//写评论


req.end()

原创粉丝点击