從頭開始本身寫一個 Express

1. Express 介紹

Express 是一個小巧且靈活的 Node.js Web應用框架,它有一套健壯的特性,可用於開發單頁、多頁和混合Web應用。css

2. Express 的應用

2.1 安裝express

npm安裝html

$ npm install express
2.2 使用express

建立http服務linux

//引入express
var express = require('express');
//執行express**函數
var app = express();
//監聽端口
app.listen(3000);
2.3 express的get方法

根據請求路徑來處理客戶端發出的GET請求git

  • 第一個參數path爲請求的路徑github

  • 第二個參數爲處理請求的回調函數shell

app.get(path,function(req, res));

get方法使用:express

//引入express
var express = require('./express');
//執行express函數
var app = express();
//監聽端口
app.get('/hello', function (req,res) {
   res.end('hello');
});
app.get('/world', function (req,res) {
    res.end('world');
});
app.get('*', function (req,res) {
    res.setHeader('content-type','text/plain;charset=utf8');
    res.end('沒有找到匹配的路徑');
});
app.listen(3000);

get方法實現:npm

//聲明express函數
var express = function () {
    var app = function (req,res) {
        var urlObj  = require('url').parse(req.url,true);
        var pathname = urlObj.pathname;
        var method = req.method.toLowerCase();
        //找到匹配的路由
        var route = app.routes.find(function (item) {
            return item.path==pathname&&item.method==method;
        });
        if(route){
            route.fn(req,res);
        }
        res.end(`CANNOT  ${method} ${pathname}`)
    };
    //增長監聽方法
    app.listen = function (port) {
        require('http').createServer(app).listen(port);
    };
    app.routes = [];
    //增長get方法
    app.get = function (path,fn) {
        app.routes.push({method:'get',path:path,fn:fn});
    };
    return app;
};
module.exports = express;

使用 * 匹配全部路徑:json

var route = app.routes.find(function (item) {
-      return item.path==pathname&&item.method==method;
+      return (item.path==pathname||item.path=='*')&&item.method==method;
});
2.4 express的post方法

根據請求路徑來處理客戶端發出的POST請求數組

  • 第一個參數path爲請求的路徑

  • 第二個參數爲處理請求的回調函數

app.post(path,function(req,res));

post方法的使用:

//引入express
var express = require('./express');
//執行express函數
var app = express();
//監聽端口
app.post('/hello', function (req,res) {
   res.end('hello');
});
app.post('*', function (req,res) {
    res.end('post沒找到');
});
app.listen(3000);

經過linux命令發送post請求

$ curl -X POST http://localhost:3000/hello

post的實現:

增長全部請求的方法

var methods = ['get','post','delete','put','options'];
methods.forEach(function (method) {
    app[method] = function (path,fn) {
        app.routes.push({method:method,path:path,fn:fn});
    };
});
2.5 express的all方法

監聽全部的請求方法,能夠匹配全部的HTTP動詞。根據請求路徑來處理客戶端發出的全部請求

  • 第一個參數path爲請求的路徑

  • 第二個參數爲處理請求的回調函數

app.all(path,function(req, res));

all的方法使用:

var express = require('./express');
var app = express();
app.all('/hello', function (req,res) {
   res.end('hello');
});
app.all('*', function (req,res) {
    res.end('沒找到');
});
app.listen(3000);

註冊全部方法:增長all方法匹配全部method

+  var methods = ['get','post','delete','put','options','all'];

all方法的實現:對all方法進行判斷

var route = app.routes.find(function (item) {
-      return (item.path==pathname||item.path=='*')&&item.method==method;
+      return (item.path==pathname||item.path=='*')&&(item.method==method||method=='all');
});
2.6 中間件

中間件就是處理HTTP請求的函數,用來完成各類特定的任務,好比檢查用戶是否登陸、檢測用戶是否有權限訪問等,它的特色是:

  • 一箇中間件處理完請求和響應能夠把相應數據再傳遞給下一個中間件

  • 回調函數的next參數,表示接受其餘中間件的調用,函數體中的next(),表示將請求數據繼續傳遞

  • 能夠根據路徑來區分返回執行不一樣的中間件

中間件的使用方法:

增長中間件

var express = require('express');
var app = express();
app.use(function (req,res,next) {
    console.log('過濾石頭');
    next();
});
app.use('/water', function (req,res,next) {
    console.log('過濾沙子');
    next();
});
app.get('/water', function (req,res) {
    res.end('water');
});
app.listen(3000);

use方法的實現:在路由數組中增長中間件

app.use = function (path,fn) {
    if(typeof fn !='function'){
        fn = path;
        path = '/';
    }
    app.routes.push({method:'middle',path:path,fn:fn});
}

app方法中增長Middleware判斷:

- var route = app.routes.find(function (item) {
-    return item.path==pathname&&item.method==method;
- });
- if(route){
-     route.fn(req,res);
- }
var index = 0;
function  next(){
    if(index>=app.routes.length){
         return res.end(`CANNOT  ${method} ${pathname}`);
    }
    var route = app.routes[index++];
    if(route.method == 'middle'){
        if(route.path == '/'||pathname.startsWith(route.path+'/')|| pathname==route.path){
            route.fn(req,res,next)
        }else{
            next();
        }
    }else{
        if((route.path==pathname||route.path=='*')&&(route.method==method||route.method=='all')){
            route.fn(req,res);
        }else{
            next();
        }
    }
}
next();

錯誤中間件:next中能夠傳遞錯誤,默認執行錯誤中間件

var express = require('express');
var app = express();
app.use(function (req,res,next) {
    console.log('過濾石頭');
    next('stone is too big');
});
app.use('/water', function (req,res,next) {
    console.log('過濾沙子');
    next();
});
app.get('/water', function (req,res) {
    res.end('water');
});
app.use(function (err,req,res,next) {
    console.log(err);
    res.end(err);
});
app.listen(3000);

錯誤中間件的實現:對錯誤中間件進行處理

function  next(err){
    if(index>=app.routes.length){
        return res.end(`CANNOT  ${method} ${pathname}`);
    }
    var route = app.routes[index++];
+    if(err){
+        if(route.method == 'middle'&&route.fn.length==4){
+            route.fn(err,req,res,next);
+        }else{
+            next(err);
+        }
+    }else{
        if(route.method == 'middle'){
            if(route.path == '/'||pathname.startsWith(route.path+'/')|| pathname==route.path){
                route.fn(req,res,next)
            }else{
                next();
            }
        }else{
            if((route.path==pathname||route.path=='*')&&(route.method==method||route.method=='all')){
                route.fn(req,res);
            }else{
                next();
            }
        }
+    }
}
2.7 獲取參數和查詢字符串
  • req.hostname 返回請求頭裏取的主機名

  • req.path 返回請求的URL的路徑名

  • req.query 查詢字符串

//http://localhost:3000/?a=1
app.get('/',function(req,res){
    res.write(JSON.stringify(req.query))
    res.end(req.hostname+" "+req.path);
});

具體實現:對請求增長方法

+     req.path = pathname;
+     req.hostname = req.headers['host'].split(':')[0];
+     req.query = urlObj.query;
2.8 獲取params參數

req.params 匹配到的全部路徑參數組成的對象

app.get('/water/:id/:name/home/:age', function (req,res) {
    console.log(req.params);
    res.end('water');
});

params實現:增長params屬性

methods.forEach(function (method) {
    app[method] = function (path,fn) {
        var config = {method:method,path:path,fn:fn};
        if(path.includes(":")){
            //是路徑參數 轉換爲正則
            //而且增長params
            var arr = [];
            config.path   = path.replace(/:([^\/]+)/g, function () {
                arr.push(arguments[1]);
                return '([^\/]+)';
            });
            config.params = arr;
        }
        app.routes.push(config);
    };
});
+ if(route.params){
+    var matchers = pathname.match(new RegExp(route.path));
+    if(matchers){
+       var params = {};
+        for(var i = 0; i<route.params.length;i++){
+            params[route.params[i]] = matchers[i+1];
+        }
+        req.params = params;
+        route.fn(req,res);
+    }else{
+        next();
+    }
+}else{
    if((route.path==pathname||route.path=='*')&&(route.method==method||route.method=='all')){
        route.fn(req,res);
    }else{
        next();
    }
+}
2.9 express中的send方法

參數爲要響應的內容,能夠智能處理不一樣類型的數據,在輸出響應時會自動進行一些設置,好比HEAD信息、HTTP緩存支持等等

res.send([body]);

當參數是一個字符串時,這個方法會設置Content-type爲text/html

app.get('/', function (req,res) {
    res.send('<p>hello world</p>');
});

當參數是一個Array或者Object,這個方法返回json格式

app.get('/json', function (req,res) {
     res.send({obj:1});
});
app.get('/arr', function (req,res) {
 res.send([1,2,3]);
});

當參數是一個number類型,這個方法返回對應的狀態碼短語

app.get('/status', function (req,res) {
    res.send(404); //not found
    //res.status(404).send('沒有找到');設置短語
});

send方法的實現:自定義send方法

res.send = function (msg) {
    var type = typeof msg;
    if (type === 'string' || Buffer.isBuffer(msg)) {
        res.contentType('text/html').status(200).sendHeader().end(msg);
    } else if (type === 'object') {
        res.contentType('application/json').sendHeader().end(JSON.stringify(msg));
    } else if (type === 'number') {
        res.contentType('text/plain').status(msg).sendHeader().end(_http_server.STATUS_CODES[msg]);
    }
};

3. 模板的應用

3.1 安裝ejs

npm安裝ejs

$ npm install ejs
3.2 設置模板

使用ejs模版

var express = require('express');
var path = require('path');
var app = express();
app.set('view engine','ejs');
app.set('views',path.join(__dirname,'views'));
app.listen(3000);
3.3 渲染html

配置成html格式

app.set('view engine','html')
app.set('views',path.join(__dirname,'views')); 
app.engine('html',require('ejs').__express);
3.4 渲染視圖
  • 第一個參數 要渲染的模板

  • 第二個參數 渲染所須要的數據

app.get('/', function (req,res) {
    res.render('hello',{title:'hello'},function(err,data){});
});
3.5 模板的實現

讀取模版渲染

res.render = function (name, data) {
    var viewEngine = engine.viewEngineList[engine.viewType];
    if (viewEngine) {
        viewEngine(path.join(engine.viewsPath, name + '.' + engine.viewType), data, function (err, data) {
            if (err) {
                res.status(500).sendHeader().send('view engine failure' + err);
            } else {
                res.status(200).contentType('text/html').sendHeader().send(data);
            }
        });
    } else {
        res.status(500).sendHeader().send('view engine failure');
    }
}

4. 靜態文件服務器

若是要在網頁中加載靜態文件(css、js、img),就須要另外指定一個存放靜態文件的目錄,當瀏覽器發出非HTML文件請求時,服務器端就會到這個目錄下去尋找相關文件

var express = require('express');
var app = express();
var path = require('path');
app.use(express.static(path.join(__dirname,'public')));
app.listen(3000);
4.1 靜態文件服務器實現

配置靜態服務器

express.static = function (p) {
    return function (req, res, next) {
        var staticPath = path.join(p, req.path);
        var exists = fs.existsSync(staticPath);
        if (exists) {
            res.sendFile(staticPath);
        } else {
            next();
        }
    }
};

5. 重定向

redirect方法容許網址的重定向,跳轉到指定的url而且能夠指定status,默認爲302方式。

  • 參數1 狀態碼(可選)

  • 參數2 跳轉的路徑

res.redirect([status], url);
5.1 redirect使用

使用重定向

app.get('/', function (req,res) {
    res.redirect('http://www.baidu.com')
});
5.2 redirect的實現

302重定向

res.redirect = function (url) {
    res.status(302);
    res.headers('Location', url || '/');
    res.sendHeader();
    res.end();
};

6. 接收 post 響應體

安裝body-parser

$ npm install body-parser
6.1 使用body-parser

接收請求體中的數據

app.get('/login', function (req,res) {
    res.sendFile('./login.html',{root:__dirname})
});
app.post('/user', function (req,res) {
    console.log(req.body);
    res.send(req.body);
});
app.listen(3000);
6.2 req.body的實現

實現bodyParser

function bodyParser () {
    return function (req,res,next) {
        var result = '';
        req.on('data', function (data) {
            result+=data;
        });
        req.on('end', function () {
            try{
                req.body = JSON.parse(result);
            }catch(e){
                req.body = require('querystring').parse(result);
            }
            next();
        })
    }
};

源代碼地址

https://github.com/YataoZhang...

相關文章
相關標籤/搜索