我想在異步中實作一個功能。此代碼用于身份驗證,如果用戶已登錄,則無需登錄就無法訪問該頁面。我在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"});
}
}
uj5u.com熱心網友回復:
您可以簡單地將匯出的exploreRandom函式作為處理程式傳遞給您的app.get路由:
const exploreRandom = require('./path/to/explore-random-module');
app.get('/explore-random', isLoggedIn, exploreRandom);
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/383086.html
上一篇:Node.js/Intellij:httppost請求回傳代碼404
下一篇:通過節點js腳本執行有問題
