var http = require('http'); var mysql = require('mysql'); var connection = mysql.createConnection({ host : 'localhost', user : 'me', password : 'secret', }); //開始你的mysql鏈接 connection.connect(); var server = http.createServer(function (req, res) { //若是你發一個GET到http://127.0.0.1:1337/test?a=1&b=2的話 var url_info = require('url').parse(req.url, true); //檢查是否是給/test的request if(url_info.pathname === '/test'){ //把query用url encode,這樣能夠用post發送 var post_data = require('querystring').stringify(url_info.query); //post的option var post_options = { host: 'localhost', port: 1337, path: '/response_logic', method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'Content-Length': post_data.length } }; //發出post var request_made = http.request(post_options, function(response_received){ var buf_list = new Array(); response_received.on('data',function(data){ buf_list.push(data); }); response_received.on('end',function(){ var response_body = Buffer.concat(buf_list); res.end(response_body); connection.query('insert into .........',function(err,rows,fields){ //處理你的結果 }); }); }); //發出post的data request_made.end(post_data); } //這個是用來回覆上面那個post的,顯示post的數據以表示成功了。你要是有別的目標,天然不須要這一段。 else{ req.pipe(res); } }); server.listen(1337, '127.0.0.1'); //在server關閉的時候也關閉mysql鏈接 server.on('close',function(){ connection.end(); }); console.log('listening on port 1337');