所以当我登录我的网站并在同一个网址中导航(例如:localhost / 私有 / xxxx)时,res.locals.user会返回一个对象。
当我离开范围时(例如:localhost / xxxx),res.locals.user
为空。
/ app.js
...
app.use(passport.session());
app.use(require('./controllers'));
...
/ controllers / index.js
router.use('/private', require('./member.js'));
router.use('/admin', require('./admin.js'));
/* Some basic routes. */
router.get('/', function(req, res, next) {
res.render('index', { ... });
});
res.locals.user
中的登录后此处仍为空
/ controllers / member.js
router.use(function isMember(req, res, next) {
if(req.isAuthenticated()) {
res.locals.user = req.user;
return next();
}
req.flash('error', 'WHY YOU LITTLE!');
res.redirect('/login');
});
router.get('/', function(req, res, next) {
res.redirect('/private/index');
});
router.get('/something', function(req, res, next) {
res.redirect('/private/somehting');
});
router.get('/darkside', function(req, res, next) {
res.redirect('/private/darkside');
});
res.locals.user
正确返回用户,无论我导航到 / private , / private / something 还是 / private / darkside
是否导致我在使用router.use('/private', require('./member.js'));
时使用中间件路由?我该如何解决这个问题?
答案 0 :(得分:2)
res.locals
是传递给应用渲染引擎的对象。您可以在护照身份验证策略中按req.session.user = user
设置用户详细信息。这样您就可以从任何路由访问用户。
答案 1 :(得分:1)
最后我只需添加
router.use(function (req, res, next) {
if(req.isAuthenticated()) {
res.locals.user = req.user;
}
return next();
});
在我的所有路线之前并从 member.js 文件中移除res.locals.user = req.user;
所以它会给我这个:
/ controllers / index.js
router.use(function (req, res, next) {
if(req.isAuthenticated()) {
res.locals.user = req.user;
}
return next();
});
router.use('/private', require('./member.js'));
router.use('/admin', require('./admin.js'));
/* Some basic routes. */
router.get('/', function(req, res, next) {
res.render('index', { ... });
});