簡體   English   中英

expressJS中的嵌套路由

[英]nested routes in expressJS

我定義了以下路線

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
    })

})

具有為您獲取該數據的通用功能。 分開路線!

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
      })
    }
  });
})

暫無
暫無

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

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