泛式路由实现
我们把pathRegexp函数作为一个模块保存到 lib/pathRegexp.js 文件中,并给代码加入出口代码 module.exports ,下面是完整的pathRegexp.js代码:
module.exports = pathRegexp;
function pathRegexp (path){
path = path.replace(/\?(.*)$/,"")
// 这一步是把所有 * 替换成正则表达式(.*)
.replace(/((\*{1}(?=\/))|(\*{1}(?=$)))/g,"(.*)")
// 这一步是把所有 :xxx 替换成正则表达式(.*)
.replace(/(:(.*?(?=\/)))|(:(.*?(?=$)))/g,"(.*)")
// 这一步是把所有 / 路径变为匹配正则表达式的 \/ 的形式
.replace(/\//g,"\\\/")
//这一步,通过生成正则表达式 ,前后的 ^ 和 & 顾名思义,要严格匹配整个路径。
return new RegExp("^"+path+"$");
}pathRegexp模块定义好后,App.js就可以通过require("./pathRegexp")得到模块对象。
上节我们把app.get和app.post方法进行了修改,但那样还不够,因为我们不能直接保存没处理过的route路由,而应该通过pathRegexp模块进行处理,把路由转换成正则表达式的方式,然后再保存。所以还需要对app.get和app.post方法进一步修改。修改后的代码如下:
App.prototype.get = function(route,handle){
this._route_get_handles.push({route:pathRegexp(route),handle:handle})
}
App.prototype.post = function(route,handle){
this._route_post_handles.push({route:pathRegexp(route),handle:handle})
}做好这些后,还需要对App.js的部分代码进行修改, this._route_post_handles = {} 和 this._route_get_handles = {} 修改成 this._route_post_handles = [] 和 this._route_get_handles = [] 。
加入url转换为path,这里使用了node.js的核心模块url,url.parse方法可以把一个url转换为JSON对象,这个JSON对象的pathname属性是一个去掉?xx=xx的url字符串。
// 把 /abc?age=12 转为 /abc var path = url.parse(req.url).pathname;
加入一个findHandle函数用于,用于在 this._route_post_handles = [] 和 this._route_get_handles = [] 里找到客户端request.url 符合的路由处理函数。
另外,在stuwebfk0.0.3版本中,并没有处理找不到资源的情况,所以加入以下代码。
res.statusCode = 404; res.end();
下一节,列出App.js 修改后的全部代码,值得注意的是,注释后面加入“ //最新修改 ”字样,表示是今天更新过的最新代码。