iT邦幫忙

1

【Node.js】request post

Mickey 1 月前4468 瀏覽

剛開始接觸 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();


1 則留言

0
麗麗
iT邦研究生 5 級 ‧ 1 月前

希望除了心得以外可以再加一些解說~
這樣看的人也懂XDDD
如果哪天你想複習也很好複習>w<!!

我要留言

立即登入留言