KostasT February 2016

NodeJs routing middleware error

I am trying to implement a middleware that will check if a user is authenticated before the server delivers a page. Although it looks like the process of doing this is simple, node is throwing an error which says "Can't set headers after they are sent".

My router's code is:

module.exports = function(app) {
    app.get('/', checkAuth, require('./myAuthenticatedPage').get);
    app.get('/login', require('./myLoginPage').get);
};

The myAuthenticatedPage.js:

exports.get = function(req, res) {
    res.render('index');
};

The myLoginPage.js:

exports.get = function(req, res) {
    res.render('login');
};

The checkAuth.js:

module.exports = function (req, res, next) {
    if(!req.session.user) {
        res.redirect('/login');
    }
    next();
}

Any help on this will be greatly appreciated.

Thanks

Answers


Thomas-B February 2016

If you aren't authenticated, you'll redirect the user and then try to render the index page. This causes the http headers to be sent twice, hence the error "Can't set headers after they are sent".

In checkAuth.js try:

module.exports = function (req, res, next) {
     if(!req.session.user) {
         res.redirect('/login');
     } else {
       next();
     }
}

Post Status

Asked in February 2016
Viewed 1,667 times
Voted 8
Answered 1 times

Search




Leave an answer