【Node.js】request post

刚开始接触 NodeJS,纪录一下心得

//==========汇入modules=========
var querystring = require('querystring');
var url = require('url');
var http = require('http');
var https = require('https');
var util = require('util');

//=========POST URL=========
var urlstr = 'url';

//=========POST 内容=========
var bodyQueryStr = {
    "key1": "content1",
    "key2": "content2"
};

var contentStr = JSON.stringify(bodyQueryStr);
var contentLen = Buffer.byteLength(contentStr, 'utf8');
console.log(util.format('post data: %s, with length: %d', contentStr, contentLen));
var httpModule = urlstr.indexOf('https') === 0 ? https : http;
var urlData = url.parse(urlstr);

//=========HTTP请求选项=========
var opt = {
    hostname: urlData.hostname,
    path: urlData.path,
    method: 'POST',
    headers: {
        'Content-Type': 'application/json',
        'Content-Length': contentLen
    }
};

//=========处理事件回复=========
var req = httpModule.request(opt, function(httpRes) {
        var buffers = [];
        httpRes.on('data', function(result) {
            buffers.push(result);
        });

        httpRes.on('end', function() {
            var wholeData = Buffer.concat(buffers);
            var dataStr = wholeData.toString('utf8');
            console.log('content ' + dataStr);
        });
    }).on('error', function(err) {
                    console.log('error ' + err);
        });

//=========传送资料,完成发送=========
req.write(contentStr);
req.end();