layer.js是exPRess框架的路由機制的底層數據結構。下面為主要源碼,已經刪除一些不太重要的代碼。
function Layer(path, options, fn) { if (!(this instanceof Layer)) { return new Layer(path, options, fn); } debug('new %s', path); var opts = options || {}; this.handle = fn; this.name = fn.name || '<anonymous>'; this.params = undefined; this.path = undefined; this.regexp = pathRegexp(path, this.keys = [], opts); if (path === '/' && opts.end === false) {//use的時候end為false,route是true,也就是說use增加的函數,在所有的請求都和會被執行 this.regexp.fast_slash = true; }}Layer.prototype.handle_error = function handle_error(error, req, res, next) { var fn = this.handle; if (fn.length !== 4) { // not a standard error handler return next(error);//跳過所有不是4個參數的函數,直接執行有四個參數的函數 } try { fn(error, req, res, next); } catch (err) { next(err); }};Layer.prototype.handle_request = function handle(req, res, next) { var fn = this.handle;//handle可能是用戶傳進來的函數或者是route的dispatch if (fn.length > 3) { // not a standard request handler return next();//不標準的函數,直接跳過,把執行權交給棧里的下一個函數 } try { fn(req, res, next); } catch (err) {//出錯的話把執行權交給棧里的下一個函數,并且把錯誤的對象傳過去 next(err); }};核心的方法為上面的三個,其中還有一個match方法是用于判斷路徑是否匹配和提取url里的參數的。 1.首先我們看一下構造函數Layer,該函數返回一個對象,并在其中存儲路由路徑和對于的回調函數,該數據結構在express做路由選擇時使用。 2。前綴為handle的兩個函數根據前面的layer層的執行結果來判斷執行哪個函數,并且根據node的約定,進行相關的參數個數檢測,最后執行相關的fn回調,正常情況下是在fn函數的函數體代碼中執行next來調到下一層,如果在fn回調執行的過程中出現錯誤,則執行catch中的代碼next(err),從而執行下一個layer,并且把err參數傳到下一層。
新聞熱點
疑難解答