2017-10-12 35 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網關。但無論如何,謝謝你解釋它 –