异步添加快速路由

时间:2014-12-04 19:57:26

标签: node.js express

在我的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  );

我已经阅读了一些解决方案,其中涉及添加catch all规则并处理该函数中的路径路径,但老实说这听起来并不太好。我想继续使用app.route()作为其他路线。

1 个答案:

答案 0 :(得分:2)

捕获所有规则仍然是处理它的最佳方式。您仍然可以将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。 您可以根据需要灵活地进行,包括使用快递路线。

相关问题