欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

了不起的node.js讀書筆記之node的學習總結

 更新時間:2014年12月22日 10:09:24   投稿:hebedich  
這篇文章主要介紹了了不起的node.js讀書筆記之node的學習總結,需要的朋友可以參考下

這周做項目做得比較散(應該說一直都是這樣),總結就依據(jù)不同情境雙開吧~這篇記錄的是關于node的學習總結,而下一篇是做項目學到的web前端的知識。

1.HTTP篇

  node的HTTP模塊在第一篇時接觸過,這里來學習幾個例程中出現(xiàn)的API。

復制代碼 代碼如下:

var qs = require('querystring');

require('http').createServer(function(req, res){
    if('/' == req.url){
        res.writeHead(200, {'Content-Type': 'text/html'});
        res.end([
            '<form method="POST" action="/url">',
            '<h1>My form</h1>',
            '<fieldset>',
            '<label>Personal information</label>',
            '<p>What is your name?</p>',
            '<input type="text" name="name">',
            '<p><button>Submit</button></p>',
            '</form>',
        ].join(''));
    }else if('/url' == req.url && 'POST' == req.method){
        var body = '';
        req.on('data', function(chunk){
            body += chunk;
        });
        req.on('end', function(){
            res.writeHead(200, {'Content-Type': 'text/html'});
            res.end('<b>Your name is <b>' + qs.parse(body).name + '</b></p>');
        });
    }else{
        res.writeHead(404);
        res.end('not found');
    }
 }).listen(3000);

  creatServer([requestListener])函數(shù)的參數(shù)是一個回調函數(shù)function(req, res),其中的req(請求request)是http.IncomingMessage的一個實例,res(響應)則是http.ServerRrsponse的實例。

  我們用到了res的url、method字符串和兩個方法writeHead、end。顧名思義,url就是記錄HTTP的URL(主機名后面所有的東西),method就是記錄HTTP響應的方法。

  writeHead(statusCode, [reasonPhrase], [headers])用來發(fā)送一個http響應頭信息,此方法只有當消息到來時才被調用一次,并且必須在end這一類方法之前調用。如果你反而為之,先調用了write(chunk, [encoding])或者end([data], [encoding])方法,系統(tǒng)會自動記錄一個不易見、易變的(總之不好的)響應頭內容并調用writeHead這個方法。

  而end方法會對服務器發(fā)出消息表示響應的信息都發(fā)送完畢,所以每次響應發(fā)送完畢時必須調用這個方法。當其參數(shù)有內容(如例程)時,這個方法等于同時調用了write('內容', [encoding])和end方法。這還是相當方便的。

  接下來,例程使用了req.on來監(jiān)聽事件并綁定在req(message)上。其原型是Emitter.on(event, listener),req就是產生事件的對象,并且在在監(jiān)聽函數(shù)中this指向當前監(jiān)聽函數(shù)所關聯(lián)的EventEmitter對象。

相關文章

最新評論