title: nodejs - Weird "Can't set headers after they are sent" case
body: <p>I'm having a strange <code>Can't set headers after they are sent</code> crash on my <strong>NodeJs/Express</strong> app.</p>
  
  <p>The crashing request : <code>POST /auth/form</code></p>
  
  <h1><strong>How the request is server-side handled</strong></h1>
  
  <p>app.js</p>
  
  <pre><code>[...]
  var auth_route = require('./routes/auth');
  app.use('/auth', auth_route );
  [...]
  </code></pre>
  
  <p>auth.js</p>
  
  <pre><code>var AuthController = require('../controller/auth_controller');
  
  [...]
  
  router.post("/form", function(req, res) {
      [...]
      auth_ctrl.form_login(username, password);
  });
  </code></pre>
  
  <p>auth_controller.js</p>
  
  <pre><code>AuthController.prototype.form_login = function(username, password) {
      _this.user_model.get_by_username(username, function(user) {
          if (user == null)
              return (Response.send_204(_this.res, "User not found"))
          password.isTheSame(password, user.password, function(err, res) {
              if (err)
                  return (Response.send_error_response(_this.res, 500, "Internal server error occured, sorry about that.."));
              if (!res)
                  return (Response.send_error_response(_this.res, 401, "Wrong password"));
              // Crash seems to happen on the above 401 response which is the 67th lines of my auth_controller file (cf. callstack bellow)
              _this.start_user_session(user, function(err) {
                  if (err) 
                      return (Response.send_error_response(_this.res, 500, "Internal server error"));
                  return (Response.send_200(_this.res, "You are logged!"));
              })
          });
      })
  }
  </code></pre>
  
  <p>Response.send_error_response source code if needed</p>
  
  <pre><code>function send_error_response(res, code, message, missing_fields) {
      [..]
  
      res.header('Content-Type', 'application/json')
      res.status(code).send(JSON.stringify({
          [..]
      }));
  }
  </code></pre>
  
  <h1><strong>The callstack trace</strong></h1>
  
  <pre><code>POST /auth/form 401 2.408 ms - -
  _http_outgoing.js:356
      throw new Error('Can\'t set headers after they are sent.');
      ^
  
  Error: Can't set headers after they are sent.
      at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:356:11)
      at ServerResponse.header (C:\Users\ME\dev\app\node_modules\express\lib\response.js:719:10)
      at Object.send_error_response (C:\Users\ME\dev\app\core\lib\Response.Library.js:30:6)
      at C:\Users\ME\dev\app\controller\auth_controller.js:67:22
  </code></pre>
  
  <h1><strong>How I make this crash happen</strong></h1>
  
  <p>I keep pushing down my enter button which send a looot of requests from the same origin.</p>
  
  <p>It seems that's happening inside password callback function...</p>
  
  <p>Any suggestions ? Thanks in advance !</p>