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












0















I'm new to node.js and want to send out dataof User and Match in a single response by querying mongodb twice .



 router.get('/preview/',  checkAuth, (req, res)=> {
const errors = {};
const match = {}
User.findOne({_id: req.user.id})
.then(user => {
if (!user) {
return res.status(404).json({errors: 'Could not find a user' });
}

Match.findOne({ user: req.user.id }).then(m => {
console.log('match found!');
match = m;
}).catch(err=> res.status(404).json(err)); // <-error occures here

res.status(200).json({user, match});
})
.catch(err=> res.status(404).json(err));

});


But I get this error:



(node:8056) UnhandledPromiseRejectionWarning: Error: Can't set headers after they are sent.


How can I fix it?










share|improve this question



























    0















    I'm new to node.js and want to send out dataof User and Match in a single response by querying mongodb twice .



     router.get('/preview/',  checkAuth, (req, res)=> {
    const errors = {};
    const match = {}
    User.findOne({_id: req.user.id})
    .then(user => {
    if (!user) {
    return res.status(404).json({errors: 'Could not find a user' });
    }

    Match.findOne({ user: req.user.id }).then(m => {
    console.log('match found!');
    match = m;
    }).catch(err=> res.status(404).json(err)); // <-error occures here

    res.status(200).json({user, match});
    })
    .catch(err=> res.status(404).json(err));

    });


    But I get this error:



    (node:8056) UnhandledPromiseRejectionWarning: Error: Can't set headers after they are sent.


    How can I fix it?










    share|improve this question

























      0












      0








      0








      I'm new to node.js and want to send out dataof User and Match in a single response by querying mongodb twice .



       router.get('/preview/',  checkAuth, (req, res)=> {
      const errors = {};
      const match = {}
      User.findOne({_id: req.user.id})
      .then(user => {
      if (!user) {
      return res.status(404).json({errors: 'Could not find a user' });
      }

      Match.findOne({ user: req.user.id }).then(m => {
      console.log('match found!');
      match = m;
      }).catch(err=> res.status(404).json(err)); // <-error occures here

      res.status(200).json({user, match});
      })
      .catch(err=> res.status(404).json(err));

      });


      But I get this error:



      (node:8056) UnhandledPromiseRejectionWarning: Error: Can't set headers after they are sent.


      How can I fix it?










      share|improve this question














      I'm new to node.js and want to send out dataof User and Match in a single response by querying mongodb twice .



       router.get('/preview/',  checkAuth, (req, res)=> {
      const errors = {};
      const match = {}
      User.findOne({_id: req.user.id})
      .then(user => {
      if (!user) {
      return res.status(404).json({errors: 'Could not find a user' });
      }

      Match.findOne({ user: req.user.id }).then(m => {
      console.log('match found!');
      match = m;
      }).catch(err=> res.status(404).json(err)); // <-error occures here

      res.status(200).json({user, match});
      })
      .catch(err=> res.status(404).json(err));

      });


      But I get this error:



      (node:8056) UnhandledPromiseRejectionWarning: Error: Can't set headers after they are sent.


      How can I fix it?







      node.js






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 20 '18 at 4:48









      BabrBabr

      31019




      31019
























          1 Answer
          1






          active

          oldest

          votes


















          2














          Please have a look at the comments added in your code.



          router.get('/preview/',  checkAuth, (req, res)=> {
          const errors = {};
          const match = {}
          User.findOne({_id: req.user.id})
          .then(user => {
          if (!user) {
          return res.status(404).json({errors: 'Could not find a user' });
          }

          Match.findOne({ user: req.user.id }).then(m => {
          console.log('match found!');
          match = m;
          }).catch(err=> res.status(404).json(err)); // <-error occures here because you sent the response if error occurs

          res.status(200).json({user, match}); // this will be executed even if there is an error so it will again try to send the response
          })
          .catch(err=> res.status(404).json(err));

          });


          Improved code:



          router.get('/preview/', checkAuth, (req, res) => {
          const errors = {};
          User.findOne({ _id: req.user.id })
          .then((user) => {
          if (!user) {
          return res.status(404).json({ errors: 'Could not find a user' });
          }
          Match.findOne({ user: req.user.id })
          .then((m) => {
          console.log('match found!');
          res.status(200).json({ user, m }); // send the success response when the match found
          })
          .catch((err) => res.status(404).json(err)); // send the error response when erro thrown
          })
          .catch((err) => res.status(404).json(err));
          });





          share|improve this answer


























          • Well I changed the first line to a console.log. The error is gone, but now I get res data undefined in the front end. Any ideas?

            – Babr
            Nov 20 '18 at 4:55













          • Does the improved code block works? I have added it in the answer.

            – Niral Munjariya
            Nov 20 '18 at 4:59











          • As I said the error gone by changing the first .catch((err) => res.status(404).json(err)) to .catch(err=> console.log(err)); . But now I get TypeError: Assignment to constant variable. error instead.

            – Babr
            Nov 20 '18 at 5:00






          • 1





            That is because you try to re-assign a value to a const variable "match", just change it to let and it should work.

            – Niral Munjariya
            Nov 20 '18 at 5:16













          • Please check the improved code block, I have updated it.

            – Niral Munjariya
            Nov 20 '18 at 5:19











          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',
          autoActivateHeartbeat: false,
          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%2f53386397%2fnode-js-unhandledpromiserejectionwarning-error-cant-set-headers-after-they-ar%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









          2














          Please have a look at the comments added in your code.



          router.get('/preview/',  checkAuth, (req, res)=> {
          const errors = {};
          const match = {}
          User.findOne({_id: req.user.id})
          .then(user => {
          if (!user) {
          return res.status(404).json({errors: 'Could not find a user' });
          }

          Match.findOne({ user: req.user.id }).then(m => {
          console.log('match found!');
          match = m;
          }).catch(err=> res.status(404).json(err)); // <-error occures here because you sent the response if error occurs

          res.status(200).json({user, match}); // this will be executed even if there is an error so it will again try to send the response
          })
          .catch(err=> res.status(404).json(err));

          });


          Improved code:



          router.get('/preview/', checkAuth, (req, res) => {
          const errors = {};
          User.findOne({ _id: req.user.id })
          .then((user) => {
          if (!user) {
          return res.status(404).json({ errors: 'Could not find a user' });
          }
          Match.findOne({ user: req.user.id })
          .then((m) => {
          console.log('match found!');
          res.status(200).json({ user, m }); // send the success response when the match found
          })
          .catch((err) => res.status(404).json(err)); // send the error response when erro thrown
          })
          .catch((err) => res.status(404).json(err));
          });





          share|improve this answer


























          • Well I changed the first line to a console.log. The error is gone, but now I get res data undefined in the front end. Any ideas?

            – Babr
            Nov 20 '18 at 4:55













          • Does the improved code block works? I have added it in the answer.

            – Niral Munjariya
            Nov 20 '18 at 4:59











          • As I said the error gone by changing the first .catch((err) => res.status(404).json(err)) to .catch(err=> console.log(err)); . But now I get TypeError: Assignment to constant variable. error instead.

            – Babr
            Nov 20 '18 at 5:00






          • 1





            That is because you try to re-assign a value to a const variable "match", just change it to let and it should work.

            – Niral Munjariya
            Nov 20 '18 at 5:16













          • Please check the improved code block, I have updated it.

            – Niral Munjariya
            Nov 20 '18 at 5:19
















          2














          Please have a look at the comments added in your code.



          router.get('/preview/',  checkAuth, (req, res)=> {
          const errors = {};
          const match = {}
          User.findOne({_id: req.user.id})
          .then(user => {
          if (!user) {
          return res.status(404).json({errors: 'Could not find a user' });
          }

          Match.findOne({ user: req.user.id }).then(m => {
          console.log('match found!');
          match = m;
          }).catch(err=> res.status(404).json(err)); // <-error occures here because you sent the response if error occurs

          res.status(200).json({user, match}); // this will be executed even if there is an error so it will again try to send the response
          })
          .catch(err=> res.status(404).json(err));

          });


          Improved code:



          router.get('/preview/', checkAuth, (req, res) => {
          const errors = {};
          User.findOne({ _id: req.user.id })
          .then((user) => {
          if (!user) {
          return res.status(404).json({ errors: 'Could not find a user' });
          }
          Match.findOne({ user: req.user.id })
          .then((m) => {
          console.log('match found!');
          res.status(200).json({ user, m }); // send the success response when the match found
          })
          .catch((err) => res.status(404).json(err)); // send the error response when erro thrown
          })
          .catch((err) => res.status(404).json(err));
          });





          share|improve this answer


























          • Well I changed the first line to a console.log. The error is gone, but now I get res data undefined in the front end. Any ideas?

            – Babr
            Nov 20 '18 at 4:55













          • Does the improved code block works? I have added it in the answer.

            – Niral Munjariya
            Nov 20 '18 at 4:59











          • As I said the error gone by changing the first .catch((err) => res.status(404).json(err)) to .catch(err=> console.log(err)); . But now I get TypeError: Assignment to constant variable. error instead.

            – Babr
            Nov 20 '18 at 5:00






          • 1





            That is because you try to re-assign a value to a const variable "match", just change it to let and it should work.

            – Niral Munjariya
            Nov 20 '18 at 5:16













          • Please check the improved code block, I have updated it.

            – Niral Munjariya
            Nov 20 '18 at 5:19














          2












          2








          2







          Please have a look at the comments added in your code.



          router.get('/preview/',  checkAuth, (req, res)=> {
          const errors = {};
          const match = {}
          User.findOne({_id: req.user.id})
          .then(user => {
          if (!user) {
          return res.status(404).json({errors: 'Could not find a user' });
          }

          Match.findOne({ user: req.user.id }).then(m => {
          console.log('match found!');
          match = m;
          }).catch(err=> res.status(404).json(err)); // <-error occures here because you sent the response if error occurs

          res.status(200).json({user, match}); // this will be executed even if there is an error so it will again try to send the response
          })
          .catch(err=> res.status(404).json(err));

          });


          Improved code:



          router.get('/preview/', checkAuth, (req, res) => {
          const errors = {};
          User.findOne({ _id: req.user.id })
          .then((user) => {
          if (!user) {
          return res.status(404).json({ errors: 'Could not find a user' });
          }
          Match.findOne({ user: req.user.id })
          .then((m) => {
          console.log('match found!');
          res.status(200).json({ user, m }); // send the success response when the match found
          })
          .catch((err) => res.status(404).json(err)); // send the error response when erro thrown
          })
          .catch((err) => res.status(404).json(err));
          });





          share|improve this answer















          Please have a look at the comments added in your code.



          router.get('/preview/',  checkAuth, (req, res)=> {
          const errors = {};
          const match = {}
          User.findOne({_id: req.user.id})
          .then(user => {
          if (!user) {
          return res.status(404).json({errors: 'Could not find a user' });
          }

          Match.findOne({ user: req.user.id }).then(m => {
          console.log('match found!');
          match = m;
          }).catch(err=> res.status(404).json(err)); // <-error occures here because you sent the response if error occurs

          res.status(200).json({user, match}); // this will be executed even if there is an error so it will again try to send the response
          })
          .catch(err=> res.status(404).json(err));

          });


          Improved code:



          router.get('/preview/', checkAuth, (req, res) => {
          const errors = {};
          User.findOne({ _id: req.user.id })
          .then((user) => {
          if (!user) {
          return res.status(404).json({ errors: 'Could not find a user' });
          }
          Match.findOne({ user: req.user.id })
          .then((m) => {
          console.log('match found!');
          res.status(200).json({ user, m }); // send the success response when the match found
          })
          .catch((err) => res.status(404).json(err)); // send the error response when erro thrown
          })
          .catch((err) => res.status(404).json(err));
          });






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Nov 20 '18 at 5:17

























          answered Nov 20 '18 at 4:53









          Niral MunjariyaNiral Munjariya

          792520




          792520













          • Well I changed the first line to a console.log. The error is gone, but now I get res data undefined in the front end. Any ideas?

            – Babr
            Nov 20 '18 at 4:55













          • Does the improved code block works? I have added it in the answer.

            – Niral Munjariya
            Nov 20 '18 at 4:59











          • As I said the error gone by changing the first .catch((err) => res.status(404).json(err)) to .catch(err=> console.log(err)); . But now I get TypeError: Assignment to constant variable. error instead.

            – Babr
            Nov 20 '18 at 5:00






          • 1





            That is because you try to re-assign a value to a const variable "match", just change it to let and it should work.

            – Niral Munjariya
            Nov 20 '18 at 5:16













          • Please check the improved code block, I have updated it.

            – Niral Munjariya
            Nov 20 '18 at 5:19



















          • Well I changed the first line to a console.log. The error is gone, but now I get res data undefined in the front end. Any ideas?

            – Babr
            Nov 20 '18 at 4:55













          • Does the improved code block works? I have added it in the answer.

            – Niral Munjariya
            Nov 20 '18 at 4:59











          • As I said the error gone by changing the first .catch((err) => res.status(404).json(err)) to .catch(err=> console.log(err)); . But now I get TypeError: Assignment to constant variable. error instead.

            – Babr
            Nov 20 '18 at 5:00






          • 1





            That is because you try to re-assign a value to a const variable "match", just change it to let and it should work.

            – Niral Munjariya
            Nov 20 '18 at 5:16













          • Please check the improved code block, I have updated it.

            – Niral Munjariya
            Nov 20 '18 at 5:19

















          Well I changed the first line to a console.log. The error is gone, but now I get res data undefined in the front end. Any ideas?

          – Babr
          Nov 20 '18 at 4:55







          Well I changed the first line to a console.log. The error is gone, but now I get res data undefined in the front end. Any ideas?

          – Babr
          Nov 20 '18 at 4:55















          Does the improved code block works? I have added it in the answer.

          – Niral Munjariya
          Nov 20 '18 at 4:59





          Does the improved code block works? I have added it in the answer.

          – Niral Munjariya
          Nov 20 '18 at 4:59













          As I said the error gone by changing the first .catch((err) => res.status(404).json(err)) to .catch(err=> console.log(err)); . But now I get TypeError: Assignment to constant variable. error instead.

          – Babr
          Nov 20 '18 at 5:00





          As I said the error gone by changing the first .catch((err) => res.status(404).json(err)) to .catch(err=> console.log(err)); . But now I get TypeError: Assignment to constant variable. error instead.

          – Babr
          Nov 20 '18 at 5:00




          1




          1





          That is because you try to re-assign a value to a const variable "match", just change it to let and it should work.

          – Niral Munjariya
          Nov 20 '18 at 5:16







          That is because you try to re-assign a value to a const variable "match", just change it to let and it should work.

          – Niral Munjariya
          Nov 20 '18 at 5:16















          Please check the improved code block, I have updated it.

          – Niral Munjariya
          Nov 20 '18 at 5:19





          Please check the improved code block, I have updated it.

          – Niral Munjariya
          Nov 20 '18 at 5:19




















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53386397%2fnode-js-unhandledpromiserejectionwarning-error-cant-set-headers-after-they-ar%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







          Popular posts from this blog

          Guess what letter conforming each word

          Port of Spain

          Run scheduled task as local user group (not BUILTIN)