簡體   English   中英

使用Express和Node加載路徑的JSON配置

[英]Loading JSON config for paths using express and node

所以我有一個關於express和node.js中路由的菜鳥問題

我有一個中間件,可以加載一個JSON file ,該JSON file包含所有路徑和這些路徑的配置。 配置文件看起來像這樣

module.exports = {
"/account" :{
    template: "dashboard/account",
    page_title: "My Account",
    // more path configs....
},
"/account/:id/users" : {
    template: "dashboard/account/account-users",
    page_title: "Account Users",
    // more path configs....
}
}

創建應用時在我的應用服務器中調用的中間件方法

app.use(middleware.getRouteConfig);

看起來像這樣

var routeConfig = require('../config/route-config'); // path to the JSON above
getRouteConfig: function (req, res, next) {
    req.config = routeConfig[req.path];
    next();
},

最后我的快車路線是這樣的

app.get('/account/:id/users',  function(req, res){
  // Get the users
  // 
});

現在說我去/ account / 12345 / users

Express注意到該路線在中間有:id並轉到該路線。 但是我的中間件然后將嘗試為該路由加載config ,並且在我的JSON配置文件中找不到/ account / 12345 / users

所以我的問題是如何使用我的動態:id路徑變量加載該路由配置,並從JSON文件中獲取配置。 提前致謝

使用Google的GSON SDK實現json解析器。

您可以從以下位置找到示例代碼: http : //www.javacreed.com/gson-deserialiser-example/

對於json字符串驗證器: http : //jsonlint.com/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM