Node.js能建立http server,當然也能取得get和post的資料

不過需要querystring和url這兩個module的幫助

var server;
var ip   = "127.0.0.1";
var port = 1234;
var http = require("http");
var qs = require('querystring');
var url = require('url');

//設定http server
server = http.createServer(function (req, res) {
        //取得get資訊
        //取得url資訊
        var params  = url.parse(req.url,true);
        //取得參數json
        console.log(params.query);

        //取得post資訊(注意:post是大寫)
        if( req.method == "POST" ) {
                var postdata = "";
                //因為post資訊,是用串流的方式傳,所以需要再用字串串接串起來
                req.on('data', function(data) {
                    postdata += data;
                });

                req.on('end', function() {
                    var post_params = qs.parse(postdata);
                    console.log(post_params);
                });
        }
});

//啟動http server,監聽http行為
server.listen(port, ip);

console.log("Server running at http://" + ip + ":" + port);

Categories: Node.js