2015-06-20 62 views
2

我试图阻止用户在登录时访问某些页面,但未使用node.js登录。如何重定向,然后在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()是真的,它会重定向,然后本质上做类似于php的exit()

回答

2

您应该使用中间件。这里有一个例子:

// 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' }) 
})