gpt4 book ai didi

javascript - Node : how to implement isLoggedIn before all routes?

转载 作者:搜寻专家 更新时间:2023-11-01 00:01:23 24 4
gpt4 key购买 nike

我想写一个辅助函数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",如何解决这个问题?

最佳答案

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

.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
});

关于javascript - Node : how to implement isLoggedIn before all routes?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30486100/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com