【问题标题】:Adding express routes asynchronously异步添加快速路由
【发布时间】:2014-12-04 19:57:25
【问题描述】:

在我的 Node.js/Express 应用程序中,我想加载一些路由来异步表达。确切地说,我想从 mongodb 中检索促销代码,并根据这些代码创建动态路由。

我目前有这个代码:

var promotion = require('../models/promotion');

promotion.list(function(promotions) {
    // Loop all promotions
    _.each(promotions, function(promo) {
        app.route(promo.get('path')).get(promotion.claim);
    });
});

不幸的是,这不起作用。经过一番调试,我发现这些路由实际上是添加到路由列表中的,但是因为它们是异步加载的,所以它们是在最后添加的 'catch all' 路由之后添加的。我通过检查发现:

console.log(  app._router.stack  );

我已经阅读了一些解决方案,这些解决方案涉及在该函数中添加一条捕获所有规则并处理路由路径,但老实说,这听起来不太好。我想继续将 app.route() 用于我的其他路线。

【问题讨论】:

    标签: node.js express


    【解决方案1】:

    catch all 规则仍然是处理它的最佳方式。而且您仍然可以将 app.route() 用于其他路线。这是可以在 app.js 中使用的示例:

    function r1(req,res) { res.status(202).end(); } //todo action logic
    function r2(req,res) { res.status(202).end(); } //todo action logic
    app.set("dynamic.routes", {"/r1":r1, "/r2":r2});
    
    //this is dynamic routing function
    function handleDynamicRoutes(req,res,next) {    
        var path = req.path;
        var routes = app.get("dynamic.routes");
        if (routes[path]) {
            routes[path](req,res);
        } else {
            next();
        }
    }
    
    app.all('*', handleDynamicRoutes);
    app.use('/users', require('./routes/users')); //just an example
    app.use('/documents', require('./routes/doucments')); //ditto
    

    显然,您可以随时更改您的 dynamic.routes。 您可以根据需要灵活地进行操作,包括使用 Express 中的 Route。

    【讨论】:

    • 感谢您的回答!经过一番搜索,恐怕你是对的:)。我担心包罗万象的路线可能对性能不利,因为我读到了这个:stackoverflow.com/questions/15344628/…。但是在我重新阅读之后,我意识到那个答案中的示例对性能不利,因为每次调用都会检查数据库。
    猜你喜欢
    • 2018-07-09
    • 2012-02-04
    • 1970-01-01
    • 2018-09-09
    • 2019-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-28
    相关资源
    最近更新 更多