让express的路由支持module, controller, action格式
发布于 11 年前 作者 saber 7576 次浏览 最后一次编辑是 8 年前

很多mvc框架都有controller和action的概念,很多后端程序员也比较熟悉,我一般是这样解决的

router.js

var siteController = require('./site.js');
var routingTable={
  default:{site:siteController}
};

var dispatch = function(module,controller,action,req,res, next) {
    if (module[controller]){
        if (module[controller][action]){
            var index = 0;
            var handles = module[controller][action];
            var next_handle = function(err){
                if (err){
                    next(err);
                }
                else{
                    var handle = handles[index++];
                    if(!handle){
                        next(err);
                    }
                    else{
                        handle(req,res, next_handle);
                    }
                }
            };

            next_handle();
        }
        else{
            next();
        }
    }
    else{
        next();
    }
};

exports.route = function(module, controller, action, req, res, next){
    if(routingTable[module]){
        dispatch(routingTable[module], controller, action, req, res, next);
    }
    else{
        next();
    }
};

site.js

var index_filter = function(req,res, next){};
var index = function(req, res, next){
  res.render('index', {});
};
module.exports = {
  index:[index_filter, index]
};

app.js

var router = require(’./roter.js’); // Routes app.get(’/’, function(req, res, next){ router.route(‘default’, ‘site’, ‘index’, req, res, next); });

app.all('/:controller', function(req, res, next){
     router.route('default', req.params.controller, 'index', req, res, next);
});

app.all('/:controller/:action', function(req, res, next){
    router.route('default', req.params.controller, req.params.action, req, res, next);
});

app.get('/:controller/:action/:id', function(req, res, next){
    router.route('default', req.params.controller, req.params.action, req,res, next);
});

app.all('/:module/:controller/:action', function(req, res, next){
    router.route(req.params.module, req.params.controller, req.params.action, req, res, next);
});
3 回复

欠缺一些项目测试的经验。

欠缺一些项目测试的经验。

回到顶部