繁体   English   中英

从另一个 function node.js 返回 boolean 值

[英]returning boolean value from another function node.js

我有一个名为admin.js的文件,它有一个BOOLEAN根据表中的ROLE列是否设置为ADMIN来执行返回 BOOLEAN 的操作。 问题是,我试图在另一个 function 中获得这个 boolean。

admin.js function

  const adminCheck = async (req, res, callback) => {
    console.log(“one”)
    await UtilRole.roleCheck(req, res, ‘ADMIN’, (response) =>  {
        if(response) {
            console.log(“one: true”)
             return true
         } else {
            console.log(“one: false”)
            return false
            //  return callback(null, false)
         }
     })
    }
    module.exports = {
    adminCheck
    }

在上面的 function 中,它返回真或假取决于用户是什么,但我不确定如何将该值放入 index.js function,如下所示:

然后在我的 index.js 中,我有这个:

 router.get(‘/viewRegistration’, auth.ensureAuthenticated, function(req, res, next) {

      const user = JSON.parse(req.session.passport.user)
      var query =  “SELECT * FROM tkwdottawa WHERE email = ‘” + user.emailAddress + “’”;
        console.log(“EMAIL ADDRESS user.emailAddress: ” + user.emailAddress)

        ibmdb.open(DBCredentials.getDBCredentials(), function (err, conn) {
          if (err) return res.send(‘sorry, were unable to establish a connection to the database. Please try again later.’);
          conn.query(query, function (err, rows) {
            if (err) {
            Response.writeHead(404);
          }

           res.render(‘viewRegistration’,{page_title:“viewRegistration”,data:rows, user});

          return conn.close(function () {
            console.log(‘closed /viewRegistration’);

          });
          });
        });
      //res.render(‘viewRegistration’, { title: ‘Express’, user });
    })

现在我的问题是,如何在index.js/viewregistration function 中调用truefalse的返回结果?

据我从您的问题中了解到,您需要一个中间件。 如果我是你,我会使用这样的中间件。

const UtilRole = require('path/UtilRole')

function adminCheck() {
  return (req, res, next) => {

    console.log('one');

    UtilRole.roleCheck(req, res, 'ADMIN', (response) => {
      if (response) {
        console.log('one: true');
        req.isAdmin = true; // This is how you get the boolean
        return next(); // With next() you left from the middleware
      } else {
        console.log('one: false');
        req.isAdmin = false; 
        return next();
      }
    })
  }
}


module.exports = {
  adminCheck
}

index.js看起来像这样

const { adminCheck } = require('path/admin');

router.get('/viewRegistration', adminCheck, auth.ensureAuthenticated,  function(req, res, next) {

  const isAdmin = req.isAdmin; // Voila, here yours boolean from admin.js

  ...
})

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM