【发布时间】:2021-12-16 12:01:57
【问题描述】:
我想异步实现一个函数。此代码用于身份验证,如果用户已登录,则无需登录就无法访问该页面。我在 app.js 文件中的代码有效,有 isLoggedOut 函数,我可以在其中实现,所以这段代码正在运行,但我想将此代码复制到我的 controller.js 。
app.js 中的工作代码:
app.get('/explore-random', isLoggedIn, (req, res) => {
const count = Recipe.find().countDocuments();
const random = Math.floor(Math.random() * count);
const recipe = Recipe.findOne().skip(random).exec();
res.render('explore-random', { title: 'Cooking Blog - Explore Random', recipe } );
})
controller.js,我想在其中实现isLoggedOut 函数到exploreRandom
function isLoggedIn(req, res, next) {
if (req.isAuthenticated()) return next();
res.redirect('/login');
}
function isLoggedOut(req, res, next) {
if (!req.isAuthenticated()) return next();
res.redirect('/home');
}
/**
* GET /explore-random
* Explore Random
*/
exports.exploreRandom = async (req, res) => {
try {
let count = await Recipe.find().countDocuments();
let random = Math.floor(Math.random() * count);
let recipe = await Recipe.findOne().skip(random).exec();
res.render('explore-random', { title: 'Cooking Blog - Explore Random', recipe } );
} catch (error) {
res.status(500).send({message: error.message || "Error Occured"});
}
}
【问题讨论】:
-
实现看起来不错,有什么问题?
标签: node.js express async-await routes controller