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

Loading JSON config for paths using express and node

本文关键字:加载 JSON 配置 路径 express node 使用      更新时间:2023-09-26

所以我有一个关于express和node.js中路由的小问题

我有一个中间件,它加载一个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文件中获取配置。提前感谢

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

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

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