title: Cannot set headers after they are sent to the client when I try to make an update request
body: <p>I am trying to create a CRUD. I have the UPDATE created, but when I try to request from postman, I get the following error:</p>
  
  <blockquote>
    <p>Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent
    to the client
        at ServerResponse.setHeader (_http_outgoing.js:526:11)
        at ServerResponse.header (E:\freebooks-core-api\node_modules\express\lib\response.js:771:10)
        at ServerResponse.send (E:\freebooks-core-api\node_modules\express\lib\response.js:170:12)
        at ServerResponse.json (E:\freebooks-core-api\node_modules\express\lib\response.js:267:15)
        at ServerResponse.send (E:\freebooks-core-api\node_modules\express\lib\response.js:158:21)
        at Object.exports.success (E:\freebooks-core-api\network\response.js:3:6)
        at E:\freebooks-core-api\components\book\network.js:32:18
        at processTicksAndRejections (internal/process/task_queues.js:97:5) {   code:
    'ERR_HTTP_HEADERS_SENT' } (node:2844)
    UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]:
    Cannot set headers after they are sent to the client
        at ServerResponse.setHeader (_http_outgoing.js:526:11)
        at ServerResponse.header (E:\freebooks-core-api\node_modules\express\lib\response.js:771:10)
        at ServerResponse.send (E:\freebooks-core-api\node_modules\express\lib\response.js:170:12)
        at ServerResponse.json (E:\freebooks-core-api\node_modules\express\lib\response.js:267:15)
        at ServerResponse.send (E:\freebooks-core-api\node_modules\express\lib\response.js:158:21)
        at Object.exports.error (E:\freebooks-core-api\network\response.js:12:6)
        at E:\freebooks-core-api\components\book\network.js:34:16
        at processTicksAndRejections (internal/process/task_queues.js:97:5) (node:2844)
    UnhandledPromiseRejectionWarning: Unhandled promise rejection. This
    error originated either by throwing inside of an async function
    without a catch block, or by rejecting a promise which was not handled
    with .catch(). To terminate the node process on unhandled promise
    rejection, use the CLI flag <code>--unhandled-rejections=strict</code> (see
    <a href="https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode" rel="nofollow noreferrer">https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode</a>).
    (rejection id: 1) (node:2844) [DEP0018] DeprecationWarning: Unhandled
    promise rejections are deprecated. In the future, promise rejections
    that are not handled will terminate the Node.js process with a
    non-zero exit code.</p>
  </blockquote>
  
  <p>As I read in the error, this comes from the following files:</p>
  
  <p><strong>response.js</strong> in my network folder</p>
  
  <pre><code>exports.success = function (req, res, data, status) {
    res.status(status || 200)
      .send({
        error: '',
        data
      })
  }
  
  exports.error = function (req, res, error, status, log) {
    console.log(log)
    res.status(status || 500)
      .send({
        error,
        data: ''
      })
  }
  </code></pre>
  
  <p>and <strong>network.js</strong> in my book (component) folder:</p>
  
  <pre><code>const router = require('express').Router()
  const response = require('../../network/response')
  const controller = require('./controller')
  
  router.get('/', function (req, res) {
      controller.getBooks()
          .then( data =&gt; {
              response.success(req, res, data, 200)
          })
          .catch( err =&gt; {
              response.error(req, res, 'Unexpected Error', 500, err)
          })
  })
  
  router.post('/', function (req, res) {
    const book = req.body
    console.log(book)
    controller.addBook(book).then( data =&gt; {
      response.success(req, res, book, 201)
    })
      .catch(err =&gt; {
        response.error(req, res, 'Internal error', 500, err)
      })
  })
  
  router.patch('/:id', function(req, res) {
    const { id } = req.params
    console.log(id)
    const book = req.body
    controller.updateBook(id, book)
      .then( data =&gt; {
          response.success(req, res, data, 200)
      }).catch( err =&gt; {
        response.error(req, res, 'Internal error', 500, err)
      }) 
    res.send('Ok')
  })
  
  module.exports = router
  </code></pre>
  
  <p>but since I am calling the <strong>controller</strong> and the error is running on that line, this is the code:</p>
  
  <pre><code>const store = require('./store')
  
  function getBooks () {
    return new Promise((resolve, reject) =&gt; {
  
      resolve(store.list())
    })
  }
  
  function addBook (book) {
    return new Promise((resolve, reject) =&gt; {
      if (!book) {
        reject('I reject')
        return false
      } else {
  
        resolve(book)
        store.add(book)
      }
    })
  }
  
   function updateBook (id, book) {
    return new Promise( async (resolve, reject) =&gt; {
        if (!id || !book) {
            reject('Invalid data')
            return false
        } else {
          const result = await store.update(id, book)
          resolve(result)
        }
  
    })
  }
  
  function deleteBook (id) {
    return new Promise( async (resolve, reject) =&gt; {
        if (!id) {
            reject('Invalid data')
            return false
        } else {
          const result = await store.update(id)
          resolve(result)
        }
  
    })
  }
  
  module.exports = {
    addBook,
    getBooks,
    updateBook,
    deleteBook
  }
  </code></pre>
  
  <p>finally the <strong>store</strong></p>
  
  <pre><code>const db = require('mongoose')
  const Model = require('./model')
  
  db.Promise = global.Promise
  db.connect(`mongodb+srv://fewtwtwfwe:efwefwecwecw@ferwrtervsefwg/test?retryWrites=true&amp;w=majority`, {
      useNewUrlParser: true,
      useUnifiedTopology: true
  }).then( () =&gt; {
      console.log(`Database connected`)
  }).catch( err =&gt; {
      console.error(err)
  })
  
  function addBook(book) {
      const myBook = new Model(book)
      myBook.save()
  }
  
  async function getBooks() {
     const books =  await Model.find()
     return books
  }
  
  async function updateBook(id, book) {
      const foundBook = await Model.findOne({
          '_id':id
      })
      foundBook.book = book
      const newBook = await foundBook.save()
      return newBook
  }
  
  async function deleteBook(id) {
      const foundBook = await Model.findOne({
          '_id':id
      })
  }
  
  
  module.exports = {
      add: addBook,
      list: getBooks,
      update: updateBook,
      delete: deleteBook,
  }
  </code></pre>
  
  <p>I modified the data of the connection to the database, because I am sure that the error does not lie there, I have made other requests and apparently everything is fine. Any idea?</p>