從零開始學習Node.js例子一 http get和post


httpserverrequestget.js

/*
獲取GET請求內容
由於GET請求直接被嵌入在路徑中,URL是完整的請求路徑,包括了?后面的部分,因此你可以手動解析后面的內容作為GET請求的參數。
node.js中url模塊中的parse函數提供了這個功能。
 */
var http = require('http');
var url = require('url');
var util = require('util');

http.createServer(function(req, res){
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end(util.inspect(url.parse(req.url, true)));
}).listen(3000);

//在瀏覽器中訪問http://localhost:3000/user?name=joey&email=joey@joey.com 然后查看返回結果

 

httpserverrequestpost.js

/*
POST請求的內容全部的都在請求體中,http.ServerRequest並沒有一個屬性內容為請求體,原因是等待請求體傳輸可能是一件耗時的工作,
比如上傳文件,而很多時候我們可能並不需要理會請求體的內容,惡意的POST請求會大大消耗服務器的資源,所有node.js默認是不會解析請求體的,
當你需要的時候,需要手動來做。
 */
var http = require('http');
var querystring = require('querystring');
var util = require('util');

http.createServer(function(req, res){
    var post = '';     //定義了一個post變量,用於暫存請求體的信息

    req.on('data', function(chunk){    //通過req的data事件監聽函數,每當接受到請求體的數據,就累加到post變量中
        post += chunk;
    });

    req.on('end', function(){    //在end事件觸發后,通過querystring.parse將post解析為真正的POST請求格式,然后向客戶端返回。
        post = querystring.parse(post);
        res.end(util.inspect(post));
    });
}).listen(3000);

注意:不要在真正的生產應用中使用上面這種簡單的方法來獲取POST請求,因為它有嚴重的效率問題和安全問題,這只是一個幫你理解的示例。

 

知識擴展:util.inherits繼承

/*
 util.inherits
 定義了一個基礎對象Base和一個繼承自Base的Sub,Base有三個在構造函數內定義的屬性和一個原型中定義的函數,通過util.inherits實現繼承
 注意,Sub僅僅繼承了Base在原型中定義的函數,而構造函數內部創造的base屬性和sayHello函數都沒有被Sub繼承。
 */
var util = require('util');

function Base(){
    this.name = 'base';
    this.base = 1991;

    this.sayHello = function(){
        console.log('Hello ' + this.name);
    };
}

Base.prototype.showName = function(){
    console.log(this.name);
};

function Sub(){
    this.name = 'sub';
}

util.inherits(Sub, Base);

var objBase = new Base();
objBase.showName();
objBase.sayHello();
console.log(objBase);

var objSub = new Sub();
objSub.showName();
//objSub.sayHello();
console.log(objSub);

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM