title: res.json Can't set headers after they are sent
body: <p>I'm learning node Js and i'm trying to do a simple subscribe/log_in app.
  I'm having issue with res.json not working as intended.</p>
  
  <p>Got this error when i'm trying to subscribe : <strong>Can't set headers after they are sent</strong></p>
  
  <p>This is my server side script : </p>
  
  <pre><code>var express = require('express');
  var swig = require('swig');
  var ent = require('ent');
  var bodyParser = require('body-parser');
  var mongoose = require('mongoose');
  var session = require('express-session');
  
  var app = express();
  
  // Environnement
  app.set('port', process.env.PORT || 3000);
  app.use(bodyParser.json());
  app.use(bodyParser.urlencoded({ extended: true }));
  app.use("/public", express.static(__dirname + "/public"));
  app.engine('html', swig.renderFile);
  app.set('view engine', 'html');
  app.set('views', __dirname + '/views');
  app.set('view cache', false);
  swig.setDefaults({ cache: false });
  app.use(session({
      secret: 'poussixthetruefighteroftheparadise',
      saveUninitialized: true,
      resave: true
  }));
  
  //MongoDB
  var db = mongoose.connect('mongodb://127.0.0.1:27017/maBase');
  var userSchema = new mongoose.Schema({
      login:  String,
      mail: String,
      password: String
  });
  var user = db.model('user', userSchema)
  
  // variables globales
  var state;
  
  
  
  
  // Page Principale
  app.get('/', function(req,res){
  
      if (req.session.user) {
          res.render('accueil.html',{});
      } else {
          res.redirect('/connection');
      }
  
  });
  
  // Page connection
  app.route('/connection')
      .get(function(req, res) {
  
          res.render('index.html',{});
  
          if (req.session.state) {
              res.json({state: req.session.state});
          }
  
      })
      .post(function(req, res) {
  
          user.find({login: req.body.login, password: req.body.password}).limit(1).exec(function (err, users) {
  
              if (err) { console.log(err) };
  
              if (!users.length) {
  
                  console.log('connection pas ok');
  
                  res.json({state: '5'});
  
              }
              else {
  
                  console.log('connection ok');
                  res.redirect('/');
  
              }
  
          });
  
      });
  
  
  // Ajouter Utilisateur
  app.post('/connection/ajouter', function(req,res){
  
      var login = req.body.login;
      var mail = req.body.mail;
  
      user.find({$or: [{login: login}, {mail: mail}]}).limit(1).exec(function (err, users) {
  
          if (err) { console.log(err) };
  
          if (!users.length) {
  
              console.log('login et mail ok');
  
              if (req.body.password == req.body.password2) {
  
                  if (req.body.password.length &gt; 6) {
  
                      var values = new user({
                              login: ent.encode(req.body.login),
                              mail: ent.encode(req.body.mail),
                              password: ent.encode(req.body.password)
                      });
  
                      values.save(function(err, values) {
  
                          if (err) return console.error(err);
  
                          console.log('utilisateur enregistré');
  
                          req.session.state = '6';
                          res.redirect('/connection');
  
                      });
  
                  } else {
  
                      console.log('Mot de passe trop court');
  
                      req.session.state = '3';
                      res.redirect('/connection');
  
                  }
  
  
              } else {
  
                  console.log('mot de passe différent');
  
                  req.session.state = '4';
                  res.redirect('/connection');
  
              }
  
          }
  
          else {
  
              console.log('login ou mail déja utilisé');
  
              if (users[0].mail == mail) {
  
                  console.log('mail déja utilisé');
                  req.session.state = '2';
                  res.redirect('/connection');
  
              } else {
  
                  console.log('login déja utilisé');
                  req.session.state = '1';
                  res.redirect('/connection');
  
              }
  
              console.log(users);
  
          }
  
      });
  
  });
  
  
  
  
  app.listen(app.get('port'), function(){
      console.log('Express server listening on port ' + app.get('port'));
  });
  </code></pre>
  
  <p>And my client side script :</p>
  
  <pre><code>&lt;html&gt;
  &lt;head&gt;
      &lt;title&gt;test&lt;/title&gt;
      &lt;link rel="stylesheet" href="public/css/reset.css"&gt;
      &lt;link rel="stylesheet" href="public/css/connection.css"&gt;
  &lt;/head&gt;
  &lt;body&gt;
  
      &lt;div id="content"&gt;
  
          &lt;a href="http://localhost:3000"&gt;&lt;img src="public/images/icone.jpg" alt="gatsbill"&gt;&lt;/a&gt;
  
          &lt;div id="wrap"&gt;
  
              &lt;div id="espacehaut"&gt;&lt;/div&gt;
              &lt;div class="click" id="con" style="display: block;"&gt;Se connecter&lt;/div&gt;
              &lt;div class="click" id="sub" style="display: none;"&gt;S'inscrire&lt;/div&gt;
  
              &lt;div id="connection" style="display: none;"&gt;
                  &lt;div id="message1" class="message" style="display: none;"&gt;&lt;/div&gt;
                  &lt;form action="/connection/" method="post" id="form_connection"&gt;
                      &lt;input type="text" name="login" id="login" placeholder="Login" value="" required="" autofocus=""&gt;
                      &lt;input type="password" name="password" id="password" placeholder="Password" required=""&gt;
                      &lt;input type="submit" name="submit" value="Connect"&gt;
                  &lt;/form&gt;
              &lt;/div&gt;
  
              &lt;div id="subscribe" style=""&gt;
                  &lt;p id="p"&gt;Pour vous inscrire,&lt;br&gt; Veuillez remplir les champs ci-dessous&lt;/p&gt;
                  &lt;div id="message2" class="message" style="display: none;"&gt;&lt;/div&gt;
                  &lt;form action="/connection/ajouter/" method="post" id="form_inscription"&gt;
                      &lt;input type="text" name="login" placeholder="Login" value="" required="" autofocus=""&gt;
                      &lt;input type="email" name="mail" placeholder="Email" value="" required=""&gt;
                      &lt;input type="password" name="password" placeholder="Password" required=""&gt;
                      &lt;input type="password" name="password2" placeholder="Password" required=""&gt;
                      &lt;input type="submit" name="submit" value="Create account"&gt;
                  &lt;/form&gt;
              &lt;/div&gt;
  
              &lt;div id="espacebas"&gt;&lt;/div&gt;
  
          &lt;/div&gt;
      &lt;/div&gt;
  
      &lt;!-- Script --&gt;
      &lt;script src="http://code.jquery.com/jquery-1.10.1.min.js"&gt;&lt;/script&gt;
      &lt;script type="text/javascript" src="public/js/connection.js"&gt;&lt;/script&gt;
      &lt;script&gt;
  
          $.getJSON( "http://localhost:3000/connection", function(data){
              if( data.state ) {
                  state = parseInt(data.state);
                  switch (state) {
                      case 1:
                          formulaire();
                          $("#message2").text("login déja utilisé");
                          break;
  
                      case 2:
                          formulaire();
                          $("#message2").text("mail déja utilisé");
                          break;
  
                      case 3:
                          formulaire();
                          $("#message2").text("Mot de passe trop court");
                          break;
  
                      case 4:
                          formulaire();
                          $("#message2").text("mot de passe différent");
                          break;
  
                      case 5:
                          connect();
                          $("#message1").text("connection pas ok");
                          break;
  
                      case 6:
                          connect();
                          $("#message1").text("vous pouvez maintenant vous connecter");
                          break;
  
                  }
              }
          });
  
      &lt;/script&gt;
  
  &lt;/body&gt;
  &lt;/html&gt;
  </code></pre>
  
  <p>When i'm trying to subscribe with two different password this is what I have : </p>
  
  <p>A white page with only this :</p>
  
  <p>{"state":"4"}</p>
  
  <p>And of course this error in node Js console: <strong>Can't set headers after they are sent</strong></p>