2017-10-12 26 views
0

我想使用类似这样的路由。从数据库中获取特快JS的路由

例如:

routes.use((req, res, next) => { 
 
    /** 
 
    * I have an example routes from database and i was passing into variable 
 
    * I'm assign fromDb as 'api/test' 
 
    */ 
 
    var a = fromDb; 
 
    next() 
 
}) 
 

 
routes.get(a, (req, res, next) => { 
 
    console.log(req.path) 
 
})

我知道,在明年的路线a变量不从数据库获取值引起的功能范围。所以,任何想法解决这个方法。我只是想知道如果我可以用模块化这样

const DBRoutes = require('lib/example.js') 
 

 
router.get(DBRoutes, (req, res) => { 
 
    console.log(req.path) 
 
})

任何想法的最佳方法是什么?由于

回答

1

您要添加基于内容的路由在你的数据库

所以你可以做的查找,成功创建路由

如:

dbConnection.lookup(...some query) 
    .then((pathFromDB) => { 
    // where pathfromDb = /api/test 
    routes.get(pathFromDB, (req, res, next) => { 
     console.log(req.path) 
    }) 
    }); 
1

routes.use((req, res, next) => { 
 
    /** 
 
    * I have an example routes from database and i was passing into variable 
 
    * I'm assign fromDb as 'api/test' 
 
    */ 
 
    res.locals.fromDb = fromDb; 
 
    next() 
 
}) 
 

 
routes.get('/your/route', (req, res, next) => { 
 
    console.log(req.path); 
 
    console.log(res.locals.fromDb); 
 
});

这是明确传递变量通过不同的中间件的一种方式。

我不认为你可以动态地设置快递网络服务器的路线。但是,启动过程中会设置一次路由。当时您可以从数据库获取路线。

const route = await routeFromDatabase(); 
 

 
routes.get(route, (req, res, next) => { 
 
    console.log(req.path); 
 
    console.log(res.locals.fromDb); 
 
});

如果更改启动后的数据库,你将不得不重新启动该节点的应用程序。

更新2018年2月19日:用户提到用例作为API网关。这是一个值得探讨的这种使用情况:https://www.express-gateway.io/

+0

'/ your/route'/取自数据库,不是静态路由。 –

+0

@AdeFirmanFauzi明白了。更新了答案。 –

+0

感谢您更新您的答案。当你说“路线在启动过程中设置一次”时,我意识到了这一点。所以,我们现在需要在数据库发生任何变化时重新启动节点应用程序。正如你所知道的,我正在用这种方法来创建一个API网关。但无论如何,谢谢你解释它 –