【问题标题】:Implement function in async异步实现函数
【发布时间】: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


【解决方案1】:

您可以简单地将导出的 exploreRandom 函数作为处理程序传递给您的 app.get 路由:

const exploreRandom = require('./path/to/explore-random-module');

app.get('/explore-random', isLoggedIn, exploreRandom);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-06-19
    • 2017-07-31
    • 2019-06-19
    • 2013-08-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多