admin管理员组文章数量:1415119
I'm trying to write middleware for authentication. And I want this if statement to redirect the user to '/'
if they're not logged in. If they're logged in, I wan't to redirect them to '/news'.
/*Simplified for this example*/
if(rs.authenticated === true) {
next();
} else {
res.redirect('/');
}
Is there a way to do this inside of these if statements? Or do I have to write a new method? I've tried several ways with if statements but I just get redirect loops.
I'm trying to write middleware for authentication. And I want this if statement to redirect the user to '/'
if they're not logged in. If they're logged in, I wan't to redirect them to '/news'.
/*Simplified for this example*/
if(rs.authenticated === true) {
next();
} else {
res.redirect('/');
}
Is there a way to do this inside of these if statements? Or do I have to write a new method? I've tried several ways with if statements but I just get redirect loops.
Share Improve this question asked Jun 25, 2013 at 20:41 georgesampergeorgesamper 5,1795 gold badges44 silver badges60 bronze badges2 Answers
Reset to default 6The standard pattern would be for all pages requiring a logged-in user to use a middleware that verifies a logged-in user and redirects to /
if they are not logged in.
function loggedIn(req, res, next) {
if(req.authenticated === true) {
next();
} else {
res.redirect('/');
}
}
app.get('/news', loggedIn, newsRoute);
app.get('/', homeRoute);
Your problem is you are using a middleware for all routes, when you really only want to use it for protected routes, which is where your redirect loop is happening. If you want to send logged-in users to '/news' instead of '/', you can either just render the right template or do a conditional redirect in there.
function homeRoute(req, res) {
if (req.authenticated) {
return res.redirect('/news');
}
res.render('home');
}
You want to introduce a small middleware for checking if the user is logged in. You set it up on a route handler level.
Please see those SO answers:
javascript node.js next()
How does Express/Connect middleware work?
What is the parameter "next" used for in Express?
本文标签: javascriptexpressjs conditional redirectStack Overflow
版权声明:本文标题:javascript - expressjs conditional redirect - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745205986a2647641.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论