title: UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the clien
body: <p>I get error: &quot;UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client&quot;,
  guessing that the problem is with promises, but I don't understand how to fix it.</p>
  <p>How do I fix my code to avoid this error, but keep the logic and work with the database?</p>
  <pre><code>router.post(&quot;/addNote&quot;, (req, res) =&gt; {
      let currentTime = new Date();
      currentTime.setUTCHours(currentTime.getUTCHours() + 3);
      const post = new PostModel({
          title: req.body.inputHeader,
          text: req.body.inputText,
          author: req.body.author,
          createdAt: currentTime
      });
  
      post.save().then(() =&gt; {
          res.json({status: &quot;saved&quot;});
      })});
  
  router.get(&quot;/getNotes&quot;, (req, res) =&gt; {
      PostModel.find().sort({createdAt: 'descending'}).then( (err, notes) =&gt; {
          if (err)
              res.json(err);
          res.json(notes);
      });
  });
  
  
  router.delete(&quot;/deleteNote/:id&quot;, (req, res) =&gt; {
      PostModel.deleteOne(
          {
              _id: req.params.id
          }
      ).then((notes) =&gt; {
          if (notes)
              res.json({status: &quot;deleted&quot;});
          res.json({status: &quot;error while deleting&quot;});
      });
  });
  
  
  router.put(&quot;/updateNote/:id&quot;, (req, res) =&gt; {
      PostModel.findByIdAndUpdate(
          req.params.id,
          {
              $set: req.body
          },
          err =&gt; {
              if (err)
                  res.send(err);
              res.send({status: &quot;updated&quot;})
          }
      ).then((notes) =&gt; {
          if (notes)
              res.json({status: &quot;update&quot;});
          res.json({status: &quot;error while updating&quot;});
      });
  });
  
  
  router.get(&quot;/getNote&quot;, (req, res) =&gt; {
      PostModel.findOne({ _id: req.params.id}).then(post =&gt; {
          if (!post){
              res.send({error: &quot;not found&quot;});
          } else {
              res.json(post)
          }
      });
  });
  
  router.post(&quot;/authorize&quot;, (req, res) =&gt; {
      // bcrypt.hash (&quot;&quot;, saltRounds, (err, hash) =&gt; {
      //     console.log(hash);
      // });
  
      let resultAuthorization = false;
      if (req.body.login === authorization.login) {
          resultAuthorization = bcrypt.compareSync(req.body.password, authorization.password);
      }
  
      if (resultAuthorization)
          res.json({statusAuthorization: &quot;correct&quot;});
      res.json({statusAuthorization: &quot;incorrect&quot;});
  });
  
  module.exports = router;
  </code></pre>