title: Express breaking when getting concurent client calls
body: <p>Because of an error that I had in the client, my node / express API was getting the exact same PUT request twice simultaneously everytime that a form was sent.</p>
  
  <p>In response, the server was always crashing with the following error:</p>
  
  <pre><code>Error: Can't set headers after they are sent
  </code></pre>
  
  <p>Now I fixed the client so server is not crashing anymore, but I'd like to fix the API properly. Anyone could kill my server by sending two PUT requests simultaneously.</p>
  
  <p>So my question:</p>
  
  <ul>
  <li>How to best handle the "can't set headers" error with Express?</li>
  <li>What is the mistake in my server code that allowed for that error to happen in the first place?</li>
  </ul>
  
  <p>Here is my server code:</p>
  
  <p><em>server.js</em></p>
  
  <pre><code>router.route('/deals/:id').put(deal.update);
  </code></pre>
  
  <p><em>deal.js</em></p>
  
  <pre><code>var r = {};
  
  exports.update = function(req, res) {
    r = res;
    var u = {
      $set: {}
    }
    for(var x in req.body){
      if (['name','stages'].indexOf(x)&gt;=0)
      u.$set[x] = req.body[x];
    }
    Pipeline // this is a mongoose object
      .findOneAndUpdate({'_id.id':req.params.id},u,{new:true})
      .exec(respond);
  }
  
  function respond(err, data) {
    if (err) {
      return r.send(err);
    } else {
      return r.json(data);
    }
  }
  </code></pre>
  
  <p><strong>UPDATE:</strong></p>
  
  <p>The error came from how I declared a global r in order to have a single response callback outside for all of my methods.</p>
  
  <p>I fixed it by having one respond callback for every method.</p>
  
  <p>Still interested to know if I could get away with a bind(res) instead?</p>