【问题标题】:nested routes in expressJSexpressJS中的嵌套路由
【发布时间】:2017-04-08 09:34:41
【问题描述】:

我定义了以下路线

router.get('/:company', function (req, res, next) {
    // 1. call database and get company data
    // 2. render company view
})

router.get('/:company/employees', function (req, res, next) {
    // 1. call database and get company data
    // 2. call database and get employees data
    // 3. render employees view
})

如何合并这 2 条路由,以便只调用一次数据库以获取公司数据。基本上我只是想重用那个逻辑。

我正在寻找类似的东西(经过测试但不起作用)

router.get('/:company', function (req, res, next) {
    // 1. call database and get company data
    // 2. render company view

    router.get('/:company/employees', function (req, res, next) {
        // no need to call database to get company data. we already have it
        // 1. call database and get employees data
        // 2. render employees view
    })

})

【问题讨论】:

  • 你不能嵌套路由。这样做会造成破坏。起初,在父路由被第一次命中之前,该路由甚至是不活跃的,然后每次父路由被命中时都会安装一个新的路由处理程序(因此是一个重复的路由处理程序)。不能那样做。只需将通用代码移动到可以从多个路由调用的共享函数中。有趣的是,Express 路由处理程序架构以某种方式使人们忘记了将通用代码放入可以从多个地方调用的共享函数的基本编程原则。
  • @jfriend00 — "有趣的是,Express 路由处理程序架构以某种方式使人们忘记了将通用代码放入可以从多个地方调用的共享函数的基本编程原则。 " :P
  • 是的很有趣。哈哈哈。

标签: javascript express nested-routes


【解决方案1】:

有一个通用函数可以为您获取该数据。保持路线分开!

function getCompanyData(input, cb) {
  //DB operation
  return cb(data);
}

function getEmployeeData(input, cb) {
  //DB operation
  return cb(data);
}
router.get('/:company', function(req, res, next) {
  getCompanyData({
    data: data
  }, function(err, data) {
    //reder view
  });
})

router.get('/:company/employees', function(req, res, next) {
  getCompanyData({
    data: data
  }, function(err, data) {
    if (!err) {
      getEmployeeData({
        data: data
      }, function(err, data) {
        //reder view
      })
    }
  });
})

【讨论】:

  • 我建议在一个函数中处理多个异步调用时使用模块async,尤其是waterfall方法。 caolan.github.io/async/docs.html#waterfall
  • @mxncson — 我会说它“取决于”.. 对于这样的小用例,我会避免使用 async..
猜你喜欢
  • 1970-01-01
  • 2019-07-07
  • 2020-07-18
  • 1970-01-01
  • 2021-09-26
  • 2015-11-22
  • 2019-12-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多