1. 程式人生 > >node搭建伺服器

node搭建伺服器

//載入http模組,http系統模組
var http = require('http');
//create 建立  server 服務
//req request=>請求   res response=》相應
http.createServer(function(req, res) {
    var url = req.url;
    // /?username=yuonly&age=18
    // var obj = {
    //     username: yuonly,
    //     age: 18
    // }
    var index = url.indexOf('?');
    var str = url.substring(index + 1); //username=yuonly&age=18
    var params = str.split('&'); //[ 'username=yuonly', 'age=18' ]

    var obj = {};
    for (var i = 0; i < params.length; i++) {
        var item = params[i];
        var name = item.split('=')[0];
        var value = item.split('=')[1];
        obj[name] = value;
    }
    console.log(obj); //{ username: 'yuonly', age: '18' }//{ username: 'yuonly', age: '18', sex: 'boy' }

    res.write('hello world');
    res.end();
}).listen(3000, function() {
    console.log('伺服器執行在3000埠');
})