NodeJS 簡單路由中間件
//使用URL中的parse方法
var parse = require("url").parse;
//這裏只接受一個參數,就是routes對象
module.exports = function route(obj){
return function(req,res,next){
//檢查以確保req.method定義了
if(!obj[req.method]){
next();//如果未定義,調用next()並停止一切後續操作
return;
}
var routes = obj[req.method];//查找req.method對應的路徑
var url = parse(req.url);//解析URL以便跟pathname匹配
var paths = Object.keys(routes);//將req.method對應的路徑存放在數組中
//遍歷路徑
for(var i = 0;i < paths.length;i++){
var path = path[i];
var fn = routes[path];
path = path
.replace(/\//g,"\\/")
.replace(/:(\w+)/g,"([^\\/]+)");
var re = new ReqExp("^" + path + "$");
var captures = url.pathname.match(re);
//嘗試跟pathname匹配
if(captures){
//拼湊參數數組
var args = [req,res].concat(captures.slice(1));
fn.apply(null,args);
//當有相匹配的函數時,返回,以防止後續的next()的調用
return;
}
}
next();
};
}