【问题标题】:Node: how to implement isLoggedIn before all routes?节点:如何在所有路由之前实现 isLoggedIn?
【发布时间】:2015-08-09 18:05:18
【问题描述】:

我想写一个辅助函数isLoggedIn,用来判断是否有用户登录,如果登录,设置res.locals.is_logged_in = true。

var isLoggedIn = function(req, res, next) {
    User.findById(sessions.user_id, function(err, user) {
        if (err) throw err;
        return !user ? false : true;
    });
};

然后,在所有路线之前,我写

.use(express.static(path.join(__dirname, '/public')))
.use(express.static(path.join(__dirname, '/bower_components')))
.use(flash)
.use(function(req, res, next) {
    if (isLoggedIn(req, res, next)) {
        res.locals.is_logged_in = true;
        res.locals.current_user = '/users/' + req.user._id;
    } else {
        res.locals.is_logged_in = false;
    }

    res.locals.showTests = app.get('env') !== 'production' &&
    req.query.test === '1';

    next();
});

var routes = require('./routes/routes.js');
app.use('/', routes.staticPages());
app.use('/', routes.sessions(sessionHelper));
app.use('/users', routes.users(sessionHelper));

但我意识到 findById 是一个异步函数,所以我无法以这种方式获得正确的行为。

我试过了

var isLoggedIn = function(callback) {
    User.findById(sessions.user_id, function(err, user) {
        if (err) throw err;
        callback(user);
    });
};

.use(function(req, res, next) {
        sessionHelper.isLoggedIn(function(user) {
            if (!user) {
                console.log("no");
                res.locals.is_logged_in = false;
            } else {
                console.log("yes");
                res.locals.is_logged_in = true;
                res.locals.current_user = '/users/' + req.user._id;
            }
        });

        res.locals.showTests = app.get('env') !== 'production' &&
            req.query.test === '1';

        next();
    });

它也不能正常工作:在某些路由中,我打印res.locals.is_logged_in,得到值“undefined”,如何解决这个问题?

【问题讨论】:

    标签: javascript node.js asynchronous express mongoose


    【解决方案1】:

    您需要异步调用。在您的情况下,您应该使用回调:

    .use(function(req, res, next) {
        sessionHelper.isLoggedIn(function(user) {
            if (!user) {
                console.log("no");
                res.locals.is_logged_in = false;
            } else {
                console.log("yes");
                res.locals.is_logged_in = true;
                res.locals.current_user = '/users/' + req.user._id;
            }
    
            next(); // next MUST be here in order to continue AFTER db query
        });
    
        res.locals.showTests = app.get('env') !== 'production' &&
            req.query.test === '1';
    
        //next(); // remove this from here, as it makes it continue without waiting for db query
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-04-14
      • 2015-09-22
      • 1970-01-01
      • 1970-01-01
      • 2019-03-19
      • 1970-01-01
      • 2017-08-30
      • 1970-01-01
      相关资源
      最近更新 更多