如何在node.js

时间:2015-06-20 23:15:22

标签: javascript node.js redirect express

我试图阻止用户在登录时访问某些页面但未使用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(/),因此不能。{/ p>

必须有一些方法,如果req.isAuthenticated()为真,它会重定向,然后基本上做类似于php的exit()

1 个答案:

答案 0 :(得分:3)

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

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