Getting an error: cannot set headers after they are sent to the client









up vote
0
down vote

favorite












I recently added authentication to my website using bcrypt. When authenticating, bcrypt compares the passwords.



If passwords match req.session is set as a cookie and written to mongodb using connect-mongodb-session. But when redirecting to /events the app crashes and gives me an error: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client



I'm using handlebars to render my html code



auth route:



Router.get('/', (req, res) => 
res.status(200).render('login', pageTitle: 'Log In');
)

Router.post('/', (req, res) =>
//Authenticate user
const username = req.body.username;
const pass = req.body.password;

User.findOne(username: username).then((user) =>
if (user)
//Validate password
console.log(user);
console.log(user.password);
bcrypt.compare(pass, user.password).then((doMatch) =>
console.log(doMatch);
//Check if password match
if (doMatch)
//To use session use express-session package
req.session.isLoggedIn = true;
req.session.user = user;
req.session.save((err) =>
console.log(err);
res.redirect('/');
);
return res.redirect('/events');
else
res.redirect('/');

).catch((err) =>
console.log(err);
);
else
return res.redirect('/');

).catch((err) =>
console.log(err);
);

);


events route:



Router.get('/events', (req, res) => 
if (req.session.isLoggedIn)

Event.find(, (err, events) =>
res.render('events',
prods: events,
pageTitle: 'Events',
path: '/events',
hasProducts: events.length > 0
);
).catch((err) =>
console.log(err);
);

else
console.log('User not authenticated');
res.status(401).send('User not authenticated');


);









share|improve this question

























    up vote
    0
    down vote

    favorite












    I recently added authentication to my website using bcrypt. When authenticating, bcrypt compares the passwords.



    If passwords match req.session is set as a cookie and written to mongodb using connect-mongodb-session. But when redirecting to /events the app crashes and gives me an error: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client



    I'm using handlebars to render my html code



    auth route:



    Router.get('/', (req, res) => 
    res.status(200).render('login', pageTitle: 'Log In');
    )

    Router.post('/', (req, res) =>
    //Authenticate user
    const username = req.body.username;
    const pass = req.body.password;

    User.findOne(username: username).then((user) =>
    if (user)
    //Validate password
    console.log(user);
    console.log(user.password);
    bcrypt.compare(pass, user.password).then((doMatch) =>
    console.log(doMatch);
    //Check if password match
    if (doMatch)
    //To use session use express-session package
    req.session.isLoggedIn = true;
    req.session.user = user;
    req.session.save((err) =>
    console.log(err);
    res.redirect('/');
    );
    return res.redirect('/events');
    else
    res.redirect('/');

    ).catch((err) =>
    console.log(err);
    );
    else
    return res.redirect('/');

    ).catch((err) =>
    console.log(err);
    );

    );


    events route:



    Router.get('/events', (req, res) => 
    if (req.session.isLoggedIn)

    Event.find(, (err, events) =>
    res.render('events',
    prods: events,
    pageTitle: 'Events',
    path: '/events',
    hasProducts: events.length > 0
    );
    ).catch((err) =>
    console.log(err);
    );

    else
    console.log('User not authenticated');
    res.status(401).send('User not authenticated');


    );









    share|improve this question























      up vote
      0
      down vote

      favorite









      up vote
      0
      down vote

      favorite











      I recently added authentication to my website using bcrypt. When authenticating, bcrypt compares the passwords.



      If passwords match req.session is set as a cookie and written to mongodb using connect-mongodb-session. But when redirecting to /events the app crashes and gives me an error: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client



      I'm using handlebars to render my html code



      auth route:



      Router.get('/', (req, res) => 
      res.status(200).render('login', pageTitle: 'Log In');
      )

      Router.post('/', (req, res) =>
      //Authenticate user
      const username = req.body.username;
      const pass = req.body.password;

      User.findOne(username: username).then((user) =>
      if (user)
      //Validate password
      console.log(user);
      console.log(user.password);
      bcrypt.compare(pass, user.password).then((doMatch) =>
      console.log(doMatch);
      //Check if password match
      if (doMatch)
      //To use session use express-session package
      req.session.isLoggedIn = true;
      req.session.user = user;
      req.session.save((err) =>
      console.log(err);
      res.redirect('/');
      );
      return res.redirect('/events');
      else
      res.redirect('/');

      ).catch((err) =>
      console.log(err);
      );
      else
      return res.redirect('/');

      ).catch((err) =>
      console.log(err);
      );

      );


      events route:



      Router.get('/events', (req, res) => 
      if (req.session.isLoggedIn)

      Event.find(, (err, events) =>
      res.render('events',
      prods: events,
      pageTitle: 'Events',
      path: '/events',
      hasProducts: events.length > 0
      );
      ).catch((err) =>
      console.log(err);
      );

      else
      console.log('User not authenticated');
      res.status(401).send('User not authenticated');


      );









      share|improve this question













      I recently added authentication to my website using bcrypt. When authenticating, bcrypt compares the passwords.



      If passwords match req.session is set as a cookie and written to mongodb using connect-mongodb-session. But when redirecting to /events the app crashes and gives me an error: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client



      I'm using handlebars to render my html code



      auth route:



      Router.get('/', (req, res) => 
      res.status(200).render('login', pageTitle: 'Log In');
      )

      Router.post('/', (req, res) =>
      //Authenticate user
      const username = req.body.username;
      const pass = req.body.password;

      User.findOne(username: username).then((user) =>
      if (user)
      //Validate password
      console.log(user);
      console.log(user.password);
      bcrypt.compare(pass, user.password).then((doMatch) =>
      console.log(doMatch);
      //Check if password match
      if (doMatch)
      //To use session use express-session package
      req.session.isLoggedIn = true;
      req.session.user = user;
      req.session.save((err) =>
      console.log(err);
      res.redirect('/');
      );
      return res.redirect('/events');
      else
      res.redirect('/');

      ).catch((err) =>
      console.log(err);
      );
      else
      return res.redirect('/');

      ).catch((err) =>
      console.log(err);
      );

      );


      events route:



      Router.get('/events', (req, res) => 
      if (req.session.isLoggedIn)

      Event.find(, (err, events) =>
      res.render('events',
      prods: events,
      pageTitle: 'Events',
      path: '/events',
      hasProducts: events.length > 0
      );
      ).catch((err) =>
      console.log(err);
      );

      else
      console.log('User not authenticated');
      res.status(401).send('User not authenticated');


      );






      javascript node.js express






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 10 at 15:20









      articapps

      54




      54






















          1 Answer
          1






          active

          oldest

          votes

















          up vote
          1
          down vote



          accepted










          These lines are the culprit.



          req.session.save((err) => 
          console.log(err);
          res.redirect('/');
          );
          return res.redirect('/events');


          Here you pass a callback into save and immediately redirect res.redirect('/events').
          After some time when callback redirect res.redirect('/'); throws an error.






          share|improve this answer




















            Your Answer






            StackExchange.ifUsing("editor", function ()
            StackExchange.using("externalEditor", function ()
            StackExchange.using("snippets", function ()
            StackExchange.snippets.init();
            );
            );
            , "code-snippets");

            StackExchange.ready(function()
            var channelOptions =
            tags: "".split(" "),
            id: "1"
            ;
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function()
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled)
            StackExchange.using("snippets", function()
            createEditor();
            );

            else
            createEditor();

            );

            function createEditor()
            StackExchange.prepareEditor(
            heartbeatType: 'answer',
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader:
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            ,
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            );



            );













             

            draft saved


            draft discarded


















            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53240356%2fgetting-an-error-cannot-set-headers-after-they-are-sent-to-the-client%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown

























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes








            up vote
            1
            down vote



            accepted










            These lines are the culprit.



            req.session.save((err) => 
            console.log(err);
            res.redirect('/');
            );
            return res.redirect('/events');


            Here you pass a callback into save and immediately redirect res.redirect('/events').
            After some time when callback redirect res.redirect('/'); throws an error.






            share|improve this answer
























              up vote
              1
              down vote



              accepted










              These lines are the culprit.



              req.session.save((err) => 
              console.log(err);
              res.redirect('/');
              );
              return res.redirect('/events');


              Here you pass a callback into save and immediately redirect res.redirect('/events').
              After some time when callback redirect res.redirect('/'); throws an error.






              share|improve this answer






















                up vote
                1
                down vote



                accepted







                up vote
                1
                down vote



                accepted






                These lines are the culprit.



                req.session.save((err) => 
                console.log(err);
                res.redirect('/');
                );
                return res.redirect('/events');


                Here you pass a callback into save and immediately redirect res.redirect('/events').
                After some time when callback redirect res.redirect('/'); throws an error.






                share|improve this answer












                These lines are the culprit.



                req.session.save((err) => 
                console.log(err);
                res.redirect('/');
                );
                return res.redirect('/events');


                Here you pass a callback into save and immediately redirect res.redirect('/events').
                After some time when callback redirect res.redirect('/'); throws an error.







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Nov 10 at 15:27









                front_end_dev

                1,310411




                1,310411



























                     

                    draft saved


                    draft discarded















































                     


                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function ()
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53240356%2fgetting-an-error-cannot-set-headers-after-they-are-sent-to-the-client%23new-answer', 'question_page');

                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    這個網誌中的熱門文章

                    How to read a connectionString WITH PROVIDER in .NET Core?

                    Node.js Script on GitHub Pages or Amazon S3

                    Museum of Modern and Contemporary Art of Trento and Rovereto