如何redirect,然后在node.js中停止

我试图阻止用户在login时访问某些页面,而不是使用node.jslogin。

到目前为止,我有这个想法:

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

这将redirect页面,但它也将在控制台中的错误:

  Error: Can't set headers after they are sent. 

我明白,这是试图做res.render('users/login')function,但因为我已经设置页面redirect(/)所以它不能。

必须有一些方法,如果req.isAuthenticated()是真的,它将redirect,然后本质上做类似于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' }) })