form1.cn
Make a little progress every day

node.js本地向远程发起post请求,Scott老师教的

08th of January 2018 Javascript Node.js 2985

我在imooc网学习node.js,其中Scott老师教了我怎么用node.js在本地评论imooc,经过学习和测试,果然成功了,确实可以被Scott老师带坏!

const http = require('http');
const qeurystring = require('querystring');

//要发送的评论内容
var poststr = qeurystring.stringify({
    content:'我来试试用node评论!',
    cid:348
});

//组织request所需要的options参数
var options = {
    hostname: 'www.imooc.com',
    path: '/course/docomment',
    port: 80,
    method: 'POST',
    headers: {
        'Accept':'application/json, text/javascript, /*; q=0.01',
        'Accept-Encoding':'gzip, deflate, br',
        'Accept-Language':'zh-CN,zh;q=0.9,en;q=0.8',
        'Connection':'keep-alive',
        'Content-Length':poststr.length,//获取要发送内容的长度
        'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8',
        'Cookie':'imooc_uuid=xxxxxxxxxx;imooc_isnew_ct=1513846860; loginstate=1; apsid=kwNWVNAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAANTQwMzQ1NgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA0MTE2Mjc5MDRAcXEuY29tAAAAAAAAAAAAAAAAAAAAADIwMTVkMzllY2E2YmQ3YjZhYjAzZmRkYWNhZDQ0MGYyfns7Wn57O1o%3DYT; PHPSESSID=dtpuql0tli5bo7c374a9belsh0; IMCDNS=0; Hm_lvt_f0cfcccd7b1393990c78efdeebff3968=1513846861,1515376561; Hm_lpvt_f0cfcccd7b1393990c78efdeebff3968=1515379321; imooc_isnew=2; cvde=5a52cfac6ca3d-54',
        'Host':'www.imooc.com',
        'Origin':'https://www.imooc.com',
        'Referer':'https://www.imooc.com/comment/348',
        'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.62 Safari/537.36X-Requested-With:XMLHttpRequest'
    }
};

//创建request请求
var rep = 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));//chunk是否是Buffer
        console.log(typeof chunk);//chunk是什么类型:Object
    });

    res.on('end',function () {
        console.log('请求完成');
    });

});

rep.on('error',function (e) {
    console.log('error' + e.message);
});

rep.write(poststr);//将数据发送
rep.end();//必须要结束

以上代码直接贴过去是不能成功的,因为headers中的Cookie是假的,当然不能用我的帐号,得用你们自己的