使用express和node加载路径的JSON配置

时间:2014-04-11 06:53:58

标签: javascript json node.js express

所以我有一个关于在express和 node.js

中路由的noob问题。

我有一个加载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

所以我的问题是如何使用 dynamic:id路径变量加载该路由配置,并从JSON文件中获取配置。提前致谢

1 个答案:

答案 0 :(得分:0)

使用Google的GSON SDK实现json解析器。

您将找到以下示例代码:http://www.javacreed.com/gson-deserialiser-example/

对于json字符串验证器:http://jsonlint.com/

相关问题