nodejs 使用http模塊發送post請求

var http = require('http');

function post(action,send,callback){
	var options = {
	  hostname: '127.0.0.1',
	  port: 80,
	  path: action,
	  method: 'POST',
	  headers: {
		'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'/* ,
		'Content-Length': send.length */
	  }
	};
	var req = http.request(options, function (res) {
		// console.log('STATUS: ' + res.statusCode);  
		// console.log('HEADERS: ' + JSON.stringify(res.headers));  
        // 定義了一個post變量,用於暫存請求體的信息
		var body="";
		res.setEncoding('utf8');
        // 通過res的data事件監聽函數,每當接受到請求體的數據,就累加到post變量中
		res.on('data', function (chunk) {
			// console.log('BODY: ' + chunk);
            body += chunk;
		});
        // 在res的end事件觸發後,通過JSON.parse將post解析爲真正的POST請求格式,然後調用傳遞過來的回調函數處理數據
		res.on('end', function(){
			// console.log("body = "+body);
			var json = JSON.parse(body);
			callback(json);
		});
	});
	req.on('error', function (e) {
	  console.log('problem with request: ' + e.message);
	});
	req.write(send);
	req.end();
}

//調用post函數在nodejs裏發送post請求
post('/node.php',"id="+id,function(json){
	console.log(json);
});

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章