Express深刻理解與簡明實現

導讀

我有一個問題和不太成熟的想法,不知道該不應提!node

掘金既然支持目錄TOC,爲何不能把目錄放在一個顯眼的地方,好比左邊?一大片空白不用非要放在右下角和其它面板搶,emmm...正則表達式

  • express概要
    • 建立一個服務器以及分發路由
    • 簡單實現1
      • 脈絡
      • 實現路由
  • .all方法和實現
    • 應用
    • 實現
      • 在app下添加.all方法(用來存儲路由信息對象)
      • 對遍歷路由信息對象時的規則判斷作出調整
  • 中間件
    • 概要
    • 中間件和路由的異同
      • 1.都會包裝成路由信息對象
      • 2.匹配條數的不一樣
      • 3.匹配路徑上的不一樣
    • next與錯誤中間件
    • 實現
      • 在app下添加.use方法
      • 改造request方法
  • params
    • params經常使用屬性
    • params與動態路由
      • 實現
        • 動態路由與動態路由屬性的實現
        • params其它屬性的實現
  • .param方法
    • api一覽
    • 注意事項
    • 應用場景
    • 和中間件的區別
    • 實現
      • 添加param方法
      • 修改request

express概要

express是一個node模塊,它是對node中http模塊的二次封裝。express

express相較於原生http模塊,爲咱們提供了做爲一個服務器最重要的功能:路由。 路由功能能幫助咱們根據不一樣的路徑不一樣的請求方法來返回不一樣的內容api

除此以外express還支持 中間件 以及其餘相似於 req.params 這些小功能。數組

建立一個服務器以及分發路由

let express = require('express');
let  app = express();

//針對不一樣的路由進行不一樣的返回
app.get('/eg1',function(req,res){
  res.end('hello');
});
app.post('/eg1',function(req,res){
  res.end('world');
});

app.listen(8080,function(){
  console.log(`server started at 8080`);
});
複製代碼

能夠發現,引入express後會返回一個函數,咱們稱之爲express。bash

express這個函數運行後又會返回一個對象,這個對象就是包裝後的http的server對象服務器

這個對象下有不少方法,這些方法就是express框架爲咱們提供的新東東了。app

上面用到了.get方法和.post方法,get和post方法能幫助咱們對路由進行分發。框架

什麼是路由分發呢?其實就是在原生request回調中依據請求方法請求路徑的不一樣來返回不一樣的響應內容。函數

就像在上面的示例中咱們經過.get.post方法對路徑爲/eg1的請求綁定了一個回調函數, 但這個兩個回調函數不會同時被調用,由於請求方法只能是一種(get或則post或則其它)。

若是請求方法是get請求路徑是/eg1則會返回.get中所放置的回調

<<< 輸出
hello
複製代碼

不然若請求路徑不變,請求方法是post則會返回.post方法中放置的回調

<<< 輸出
world
複製代碼

簡單實現1

脈絡

咱們首先要有一個函數,這個函數運行時會返回一個app對象

function createApplication(){
  let app = function(req,res){};
  return app;
}
複製代碼

這個app對象下還有一些方法.get.post.listen

app.get = function(){}
app.post = function(){}
app.listen = function(){}
複製代碼

其中app.listen其實就是原生http中的server.listenapp就是原生中的request回調。

app.listen = function(){
  let server = http.createServer(app);
  server.listen.apply(server,arguments); //事件回調中,無論怎樣this始終指向綁定對象,這裏既是server,原生httpServer中也是如此
}
複製代碼

實現路由

咱們再來想一想app.get這些方法到底作了什麼。 其實無非定義了一些路由規則,對匹配上這些規則的路由進行一些針對性的處理(執行回調)。

上面一句話作了兩件事,匹配規則 和 執行回調。 這兩件事執行的時機是何時呢?是服務器啓動的時候嗎?不是。 是當接收到客戶端請求的時候

這意味着什麼? 當服務器啓動的時候,其實這些代碼已經執行了,它們根本不會管請求是個什麼鬼,只要服務器啓動,代碼就執行。 因此咱們須要將規則回調存起來。(相似於發佈訂閱模式)

app.routes = []; 
app.get = function(path,handler){
  app.routes.push({
    method:'get'
    ,path
    ,handler
  })
}
複製代碼

上面咱們定義了一個routes數組,用來存放每一條規則和規則所對應的回調以及請求方式,即路由信息對象

但有一個地方須要咱們優化。不一樣的請求方法所要作的事情都是相同的(只有method這個參數不一樣),咱們不可能每增長一個就重複的寫一次,請求的方法是有很是多的,這樣的話代碼會很冗餘。

//http.METHODS能列出全部的請求方法
>>>
console.log(http.METHODS.length);

<<<
33
複製代碼

So,爲了簡化咱們的代碼咱們能夠遍歷http.METHODS來建立函數

http.METHODS.forEach(method){
  let method = method.toLowerCase();
  app[method] = function(path,handler){
    app.routes.push({
      method
      ,path
      ,handler
    })
  }
}
複製代碼

而後咱們會在請求的響應回調中用到這些路由信息對象。而響應回調在哪呢? 上面咱們已經說過其實app這個函數對象就是原生的request回調。 接下來咱們只須要等待請求來臨而後執行這個app回調,遍歷每個路由信息對象進行匹配,匹配上了則執行對應的回調函數。

let app = function(req,res){
  for(let i=0;i<app.routes.length;++i){
    let route = app.routes[i];
    let {pathname} = url.parse(req.url);
    if(route.method==req.method&&route.path==pathname){
    	route.handler(req,res);
    }
  }
}
複製代碼

.all方法和實現

應用

.all也是一個路由方法,

app.all('/eg1',function(req,res){})
複製代碼

和普通的.get,.post這些和請求方法直接綁定的路由分發不一樣,.all方法只要路徑匹配得上各類請求方法去請求這個路由都會獲得響應。

還有一種更暴力的使用方式

app.all('*',function(req,res){})
複製代碼

這樣能匹配全部方法全部路勁,all! 一般它的使用場景是對那些沒有匹配上的請求作出兼容處理。

實現

在app下添加.all方法(用來存儲路由信息對象)

和通常的請求方法是同樣的,只是須要一個標識用以和普通方法區分開。 這裏是在method取了一個all關鍵字做爲method的值。

app.all = function(path,handler){
  app.routs.push({
    method:'all'
    ,path
    ,handler
  })
}
複製代碼

對遍歷路由信息對象時的規則判斷作出調整

另外還須要在request回調中對規則的匹配判斷作出一些調整

if((route.method==req.method||route.method=='all')&&(route.path==pathname||route.path=='*')){
    route.handler(req,res);
}
複製代碼

中間件

概要

中間件是什麼鬼呢?中間件嘛,顧名思義中間的件。。。emmm,咱們直接說說它的做用吧!

中間件主要是在請求和真正響應之間再加上一層處理, 處理什麼呢?好比說權限驗證、數據加工神馬的。

這裏所謂的真正響應,你能夠把它當作.get這些路由方法所要執行的那些個回調。

app.use('/eg2',function(req,res,next){
  //do something
  next();
})
複製代碼

中間件和路由的異同

1.都會包裝成路由信息對象

服務器啓動時,中間件也會像路由那樣被存儲爲一個一個路由信息對象

2.匹配條數的不一樣

路由只要匹配上了一條就會立馬返回數據並結束響應,不會再匹配第二條(原則上如此)。 而中間件只是一個臨時中轉站,對數據進行過濾或則加工後會繼續往下匹配。 So,中間件通常放在文件的上方,路由放在下方。

3.匹配路徑上的不一樣

中間件進行路徑匹配時,只要開頭匹配的上就能執行對應的回調。

這裏所謂的開頭意思是: 倘若中間件要匹配的路徑是/eg2, 那麼只要url.path是以/eg2開頭,像/eg2/eg2/a/eg2/a/b便可。(/eg2a這種不行,且必須以/eg2開頭,a/eg2則不行)

而路由匹配路徑時必須是徹底匹配,也就是說規則如果/eg2則只有/eg2匹配的上。這裏的徹底匹配實際上是針對路徑的 /的數量 來講的,由於動態路由中匹配的值不是定死的。

除此以外,中間件能夠不寫路徑,當不寫路徑時express系統會爲其默認填上/,即所有匹配。

next與錯誤中間件

中間件的回調相較於路由多了一個參數next,next是一個函數。 這個函數能讓中間件的回調執行完後繼續向下匹配,若是沒有寫next也沒有在中間件中結束響應,那麼請求會一直處於pending狀態。

next還能夠進行傳參,若是傳了慘,表示程序運行出錯,將匹配錯誤中間件進行處理且只會交由錯誤中間件處理

錯誤中間件相較於普通中間件在回調函數中又多了一個參數err,用以接收中間件next()傳遞過來的錯誤信息。

app.use('/eg2',function(req,res,next){
  //something wrong
  next('something wrong!');
})

app.use('/eg2',function(err,req,res,next){
  console.log('i catch u'+err);
  next(err); //pass to another ErrorMiddle
});

// 錯誤中間接收了錯誤信息後仍然容許接着向下傳遞

app.use('/eg2',function(err,req,res,next){
  res.end(err);
});
複製代碼

其實錯誤中間件處理完成後也能匹配路由

app.use('/eg2',function(req,res,next){
  //something wrong
  next('something wrong!');
})

app.use('/eg2',function(err,req,res,next){
  console.log('i catch u'+err);
  next(err); //pass to another ErrorMiddle
});

app.get('/eg2',function(req,res){
  //do someting
})
複製代碼

實現

在app下添加.use方法

像路由方法同樣,其實就是用來存儲路由信息對象

app.use = function(path,handler){
    if(typeof handler != 'function'){ //說明只有一個參數,沒有path只有handler
      handler = path;
      path = "/"
    }
    app.routes.push({
      method:'middle' //須要一個標識來區分中間件
      ,path
      ,handler
    });
  };
複製代碼

改造request方法

let app = function(req,res){
	const {pathname} = url.parse(req.url, true);
    let i = 0;
	function next(err){
        if(index>=app.routes.length){ //說明路由信息對象遍歷完了仍沒匹配上,給出提示
        	return res.end(`Cannot ${req.method} ${pathname}`);
        }
    	let route = app.routes[i++];
        if(err){ //是匹配錯誤處理中間件
            //先判斷是否是中間件
            if(route.method == 'middle'){
                //若是是中間件再看路徑是否匹配
                if(route.path=='/'||pathname.startsWith(route.path+'/')||route.path==pathname){
                	//再看是不是錯誤處理中間件
                    if(route.handler.length==4){
                        route.handler(err,req,res,next);
                    }else{
                        next(err);
                    }
                }else{
                    next(err);
                }
            }else{
            	next(err); //將err向後傳遞直到找到錯誤處理中間件
            }
        }else{ //匹配路由和普通中間件
            if(route.method == 'middle'){ //說明是中間件
            	if(route.path=='/'||pathname.startsWith(route.path+'/')||route.path==pathname){
                	route.handler(req,res,next);
                }else{ //此條路由沒有匹配上,繼續向下匹配
                	next();
                }
            }else{ //說明是路由
                if((route.method==req.method||route.method=='all')&&(route.path==pathname||route.path=='*')){
                //說明匹配上了
                	route.handler(req,res);
                }else{
                	next();
                }
            }
        }
    }
	next();
}
複製代碼

咱們能夠把對錯誤中間件的判斷封裝成一個函數

function checkErrorMiddleware(route){
  if(route.method == 'middle'&&(route.path=='/'||pathname.startsWith(route.path+'/')||route.path==pathname)&&route.handler.length==4){
    return true;
  }else{
    next(err);
  }
}
複製代碼

params

params經常使用屬性

express爲咱們在request回調中的req對象參數下封裝了一些經常使用的屬性

app.get('/eg3',function(req,res){
  console.log(req.hostname);
  console.log(req.query);
  console.log(req.path);
})
複製代碼

params與動態路由

app.get('/article/:artid',function(req,res){
  console.log(req.artid);
})

>>>
/article/8

<<<
8
複製代碼

實現

動態路由與動態路由屬性的實現

首先由於路由規則所對應的路徑咱們看得懂,但機器看不懂。 So咱們須要在存儲路由信息對象時,對路由的規則進行正則提煉,將其轉換成正則的規則。

...
app[method] = function(path,handler){
  let paramsNames = [];
  path = path.replace(/:([^\/]+)/g,function(/*/:aaa ,aaa*/){ 
    paramsNames.push(arguments[1]); //aaa
    return '([^\/]+)';  // /user/:aaa/:bbb 被提煉成 /user/([^\/]+)/([^\/]+)
  });
      
  layer.reg_path = new RegExp(path);
  layer.paramsNames = paramsNames;
}
...
複製代碼

咱們拿到了一個paramsNames包含全部路徑的分塊,並將每一個分塊的值做爲了一個新的param的名稱,

咱們還拿到了一個reg_path,它能幫助咱們對請求的路徑進行分塊匹配,匹配上的每個子項就是咱們新param的值。

request路由匹配部分作出修改

if(route.paramsNames){
    let matchers = pathname.match(req.reg_path);
    if(matchers){
    	let params = {};
        for(let i=0;i<route.paramsNames.length;++i){
            params[route.paramsNames[i]] = matchers[i+1]; //marchers從第二項開始纔是匹配上的子項
        }
    	req.params = params;
    }
    route.handler(req,res);
}

複製代碼

params其它屬性的實現

這裏是內置中間件,即在框架內部,它會在第一時間被註冊爲路由信息對象。

實現很簡單,就是利用url模塊對req.url進行解析

app.use(function(req,res,next){
    const urlObj = url.parse(req.url,true);
    req.query = urlObj.query;
    req.path = urlObj.pathname;
    req.hostname = req.headers['host'].split(':')[0];
    next();
});
複製代碼

.param方法

api一覽

app.param('userid',function(req,res,next,id){
  req.user = getUser(id);
  next();
});
複製代碼

next和中間件那個不是一個意思,這個next執行的話會執行被匹配上的那條動態路由所對應的回調

id爲請求時userid這個路徑位置的實際值,好比

訪問路徑爲:http://localhost/ahhh/9

動態路由規則爲:/username/userid

userid即爲9
複製代碼

注意事項

必須配合動態路由!! param和其它方法最大的一點不一樣在於,它能對路徑進行截取匹配

什麼意思呢, 上面咱們講過,路由方法路徑匹配時必須徹底匹配,而中間件路徑匹配時須要開頭同樣

param方法無需開頭同樣,也無需徹底匹配,它只須要路徑中某一個分塊(即用/分隔開的每一個路徑分塊)和方法的規則對上便可。

應用場景

當不一樣的路由中包含相同路徑分塊且使用了相同的操做時,咱們就能夠對這部分代碼進行提取優化。

好比每一個路由中都須要根據id獲取用戶信息

app.get('/username/:userid/:name',function(req,res){}
app.get('/userage/:userid/:age',function(req,res){}
app.param('userid',function(req,res,next,id){
  req.user = getUser(id);
  next();
});
複製代碼

和中間件的區別

相較於中間件它更像是一個真正的鉤子,它不存在放置的前後問題。 若是是中間件,通常來講它必須放在文件的上方,而param方法不是。

致使這樣結果的本質緣由在於,中間件相似於一個路由,它會在請求來臨時加入的路由匹配隊列中參與匹配。而param並不會包裝成一個路由信息對象也就不會參與到隊列中進行匹配,

它的觸發時機是在它所對應的那些動態路由被匹配上時纔會觸發。

實現

添加param方法

在app下添加了一個param方法,而且建立了一個paramHandlers對象來存儲這個方法所對應的回調。

app.paramHandlers = {};
app.param = function(name,handler){
    app.paramHandlers[name] = handler; //userid
};
複製代碼

修改request

修改request回調中 動態路由被匹配上時的部分

當動態路由被匹配上時,經過它的動態路由參數來遍歷paramHandlers,看是否設置了對應的param回調

if(route.paramsNames){
    let matchers = pathname.match(route.reg_path);

    if(matchers){
      let params = {};
      for(let i=0;i<route.paramsNames.length;++i){
        params[route.paramsNames[i]] = matchers[i+1];
      }
      req.params = params;
      for(let j=0;j<route.paramsNames.length;++j){
        let name = route.paramsNames[j];
        let handler = app.paramHandlers[name];
        if(handler){
        //回調觸發更改在了這裏
        //第三個參數爲next,這裏把route.handler放在了這裏,是讓param先執行再執行該條路由
          return handler(req,res,()=>route.handler(req,res),req.params[name]); 
        }else{
          return route.handler(req,res);
        }
      }

    }else{
      next();
    }
}
複製代碼

源碼

let http = require('http');
let url = require('url');

function createApplication() {
  //app其實就是真正的請求監聽函數

  let app = function (req, res) {
    const {pathname} = url.parse(req.url, true);
    let index = 0;
    function next(err){
      if(index>=app.routes.length){
        return res.end(`Cannot ${req.method} ${pathname}`);
      }
      let route = app.routes[index++];
      if(err){
        //先判斷是否是中間件
        if(route.method == 'middle'){
          //若是是中間件再看路徑是否匹配
          if(route.path=='/'||pathname.startsWith(route.path+'/')||route.path==pathname){
            //再看是不是錯誤處理中間件
            if(route.handler.length==4){
              route.handler(err,req,res,next);
            }else{
              next(err);
            }
          }else{
            next(err);
          }
        }else{
          next(err); //將err向後傳遞直到找到錯誤處理中間件
        }
      }else{
        if(route.method == 'middle'){ //中間件
          //只要請求路徑是以此中間件的路徑開頭便可
          if(route.path=='/'||pathname.startsWith(route.path+'/')||route.path==pathname){
            route.handler(req,res,next);
          }else{
            next();
          }
        }else{ //路由
          if(route.paramsNames){
            let matchers = pathname.match(route.reg_path);

            if(matchers){
              let params = {};
              for(let i=0;i<route.paramsNames.length;++i){
                params[route.paramsNames[i]] = matchers[i+1];
              }
              req.params = params;
              for(let j=0;j<route.paramsNames.length;++j){
                let name = route.paramsNames[j];
                let handler = app.paramHandlers[name];
                if(handler){ //若是存在paramHandlers 先執行paramHandler再執行路由的回調
                  return handler(req,res,()=>route.handler(req,res),req.params[name]);
                }else{
                  return route.handler(req,res);
                }
              }

            }else{
              next();
            }
          }else{
            if ((route.method == req.method.toLowerCase() || route.method == 'all') && (route.path == pathname || route.path == '*')) {
              return route.handler(req, res);
            }else{
              next();
            }
          }
        }
      }

    }
    next();

  };

  app.listen = function () { //這個參數不必定
    let server = http.createServer(app);
    //server.listen做爲代理,將可變參數透傳給它
    server.listen.apply(server, arguments);
  };
  app.paramHandlers = {};
  app.param = function(name,handler){
    app.paramHandlers[name] = handler; //userid
  };

  //此數組用來保存路由規則
  app.routes = [];
  // console.log(http.METHODS);
  http.METHODS.forEach(function (method) {
    method = method.toLowerCase();
    app[method] = function (path, handler) {
      //向數組裏放置路由對象
      const layer = {method, path, handler};
      if(path.includes(':')){
        let paramsNames = [];
        //1.把原來的路徑轉成正則表達式
        //2.提取出變量名
        path = path.replace(/:([^\/]+)/g,function(){ //:name,name
          paramsNames.push(arguments[1]);
          return '([^\/]+)';
        });
        // /user/ahhh/12
        // /user/([^\/]+)/([^\/]+)
        layer.reg_path = new RegExp(path);
        layer.paramsNames = paramsNames;
      }

      app.routes.push(layer);
    };

  });

  //all方法能夠匹配全部HTTP請求方法
  app.all = function (path, handler) {
    app.routes.push({
      method: 'all'
      , path
      , handler
    });
  };
  //添加一箇中間件
  app.use = function(path,handler){
    if(typeof handler != 'function'){ //說明只有一個參數,沒有path只有handler
      handler = path;
      path = "/"
    }
    app.routes.push({
      method:'middle' //須要一個標識來區分中間件
      ,path
      ,handler
    });
  };
  //系統內置中間件,用來爲請求和響應對象添加一些方法和屬性
  app.use(function(req,res,next){
    const urlObj = url.parse(req.url,true);
    req.query = urlObj.query;
    req.path = urlObj.pathname;
    req.hostname = req.headers['host'].split(':')[0];
    next();
  });
  return app;
}

module.exports = createApplication;
複製代碼
相關文章
相關標籤/搜索