我试图阻止用户在登录时访问某些页面,而不是使用node.js登录.
到目前为止,我有这个想法:
exports.blockIfLoggedIn = function (req, res) {
if (req.isAuthenticated()) { //passport
req.flash('error', 'Sorry but you can\'t access this page');
res.redirect('/');
}
};
MA.f.auth.blockIfLoggedIn(req, res, next);
res.render('users/login', {
title: 'Login'
});
这将重定向页面,但在控制台中也会出现以下错误:
Error: Can't set headers after they are sent.
我知道这是在尝试执行res.render(‘users / login’)功能,但是由于我已经将页面设置为redirect(/),所以不能.
必须有某种方式,如果req.isAuthenticated()为true,它将进行重定向,然后从本质上执行类似于php exit()的操作?
解决方法:
您应该使用中间件.这是一个例子:
// you can include this function elsewhere; just make sure you have access to it
var blockIfLoggedIn = function (req, res, next) {
if (req.isAuthenticated()) {
req.flash('error', 'Sorry, but you cannot access this page.')
return res.redirect('/')
} else {
return next()
}
}
// in your routes file (or wherever you have access to the router/app)
// set up your route
app.get('/users/login', blockIfLoggedIn, function (req, res) {
res.render('somePage.ext', { title: 'Login' })
})