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);
});