asynchronous添加快速路由

在我的Node.js / Express应用程序中,我想加载一些路线以asynchronous表示。 准确地说,我想从MongoDB中检索促销代码,并根据这些代码创builddynamic路由。

我目前有这样的代码:

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

不幸的是,这是行不通的。 经过一些debugging后,我发现这些路由实际上被添加到了路由列表中,但是因为它们是asynchronous加载的,所以它们被添加到最后添加的“catch all”路由之后。 我发现通过检查:

 console.log( app._router.stack ); 

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

捕捉所有的规则仍然是处理它的最好方法。 你仍然可以使用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。 您可以根据需要灵活地使用它,包括使用快速路由。