DoraCMS

您现在的位置是:首页>文档内容页

文档详情

第4天 路由——路由功能的实现

doramart 2015-09-20 18:55:31 NodeJs224876
首先要在App.js的构造函数内,加入 this._route_post_handles = {}和 this._route_get_handles = {}用于储存路由处理器。

路由功能的实现

首先要在App.js的构造函数内,加入 this._route_post_handles = {}this._route_get_handles = {}用于储存路由处理器。

然后,我们在App.js的构造器内的handle函数,做一些改动。加入 handle = self._route_get_handles[req.url] 和  handle = self._route_get_handles[req.url] 代码 ,最后 handle(req,res) 执行就可以了。

而App.prototype.get / App.prototype.post 的代码也需要修改,修改十分简单,只要把handle注入到 self._route_get_handles 或 self._route_post_handles 里即可。

App.prototype.get = function(route,handle){
    this._route_get_handles[route] = handle;
}

App.prototype.post = function(route,handle){
    this._route_post_handles[route] = handle;
}

在编码过程中,有一处BUG,值得注意,就是在App.js构造函数的顶端代码:

function App(){

    function handle(req,res){
        if(middleList.length === 0){        
        }else{
        .....

这里 if(middleList.length === 0){ 是个BUG,因为如果我们没有加入static或其他插件时,GET/POST路由处理器就不会被执行。所以删除了上面这段代码。这个代码的存在,在早期可能有用,但随着项目的迭代, 会修补很多历史性代码。

下一节,列出更改后的App.js代码。

文章评论

取消回复
登录 参与评论

评论列表(