0

I have the following route in my Express app that sets a cookie after a session has been written to the database. Then, after the session has been written the database, the route performs res.render which simply just contains a redirect in the header to take the user to /login. The problem I'm having though is that when the below function is ran I get the infamous "cant set headers after they have been sent" error and I'm a little confused as to why this is happening?

For cookies, I'm using cookies.

Thanks in advance!

.get(function (req, res) {

        userTable.find({_id: req.query.id}, function (err, obj) {

            var newSession = new sessionsTable({
                for_user: obj[0]._id
            });

            var cookies = new Cookies(req, res);

            newSession.save(function (err, session) {
                if (err)
                    console.log(err)

                cookies 
                    .set('_sessionStarted', true, { httpOnly: false, overwrite: false });
            });

        });

        res.render('activate-session.ejs');

    });
leaksterrr
  • 3,800
  • 7
  • 34
  • 65
  • Remove .ejs on render function res.render('activate-session'); – Muhammad Ali Jul 12 '14 at 07:40
  • That didn't do anything. – leaksterrr Jul 12 '14 at 07:41
  • OK use res.render just after cookies.set() .. inside the body of SAVE – Muhammad Ali Jul 12 '14 at 07:45
  • This worked, thanks. Could you shed some light on why this was happening? – leaksterrr Jul 12 '14 at 07:47
  • 1
    This happens because `userTable.find` is an async operation, results of which are available in the callback after some time. By the time you reach `res.render('activate-session');` which is not inside the callback, the callback of `find` operation would not have been invoked. Hence you need to wait for the `find` operation to complete before you can proceed. Hope this helps. – vmx Jul 13 '14 at 07:35

1 Answers1

1

use res.render inside the function of Save. there is Async function , this is multi-threading function.

you can see some example search with google or http://nathansjslessons.appspot.com/lesson?id=1085

How to write asynchronous functions for Node.js

newSession.save(function (err, session) {
            if (err)
                console.log(err)

            cookies 
                .set('_sessionStarted', true, { httpOnly: false, overwrite: false });
res.render('activate-session.ejs');           
 });
Community
  • 1
  • 1
Muhammad Ali
  • 1,992
  • 1
  • 13
  • 20