gpt4 book ai didi

javascript - ExpressJS 中的嵌套路由

转载 作者:行者123 更新时间:2023-11-28 18:15:57 25 4
gpt4 key购买 nike

我定义了以下路由

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

})

最佳答案

Have a common function to get that data for you. Keep routes separate!

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

关于javascript - ExpressJS 中的嵌套路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40780328/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com