Error: Can't set headers after they are sent after I have initialized a session

Viewed 70

Exactly the problem starts after a few times I navigate with the session started by the page, and gives me the error can not header after they are send until I delete the cookie from the session. I already have several days with this error and so far I do not know what is wrong.

Model:

'use strict'

var Usuarios = require('./consultora-connection').Usuarios,
Anuncios = require('./consultora-connection').Anuncios,
Suscriptores = require('./consultora-connection').Suscriptores,
Contactos = require('./consultora-connection').Contactos,
bcrypt = require('bcrypt-nodejs'),
nodemailer = require('nodemailer'),
ip = require('ip'),
passport = require('passport'),
Consultora = ()=>{}

Consultora.inicio = (cb)=>{
cb()
}

Controller:

'use strict'

var ConsultoraModel = require('../models/consultora-model'),
HtmlEntities = require('html-entities').AllHtmlEntities,
entities = new HtmlEntities(),
md5 = require('md5'),
fs = require('fs'),
ConsultoraController = ()=>{}

ConsultoraController.inicio = (req, res, next)=>{

    ConsultoraModel.inicio(()=>{
        let locals={

            title: `Now Consultora`,
            description: `El mejor lugar para encontrar de todo.`,
            keywords:"now consultora, desarrollo web, diseño publicitario, google adwords, facebook ads, asesorias",
            data:{
                    sesion: (req.user) ? true : false
                }
        }
        if(!req.user){//I have to delete the cookie after closing the session so that the problem does not continue
            res.clearCookie('connect.sid', { path: '/' });
        }
        res.render('index', locals)
    })
}

Router:

'use strict'

var ConsultoraController = require('../controllers/consultora-controller'),
express = require('express'),
passportConfig = require('../models/passport'),
multer = require('multer'),
storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, './public/img/anuncios')
  },
  filename: function (req, file, cb) {
    cb(null, req.body.id+"-"+file.fieldname+'.png')
  }
}),
upload = multer({storage: storage, fileFilter: function (req, file, cb) {
         if (!file.originalname.match(/\.(png|jpg)$/)) {
                    return cb(new Error('Error en el tipo de archivo.'));
         }

         cb(null, true);
         }
         }),
cpUpload= upload.fields([{name:'img1', maxCount: 1}]),
router = express.Router()



router.get('/', ConsultoraController.inicio)

index:

extends layout
block content
-if (data.sesion)
    include header3.jade
-else
    include header1.jade
input(type="hidden").efecto
div#particles-js
//--------------------------------------- CAROUSEL--------------------------------------------------------------
div#carouselExampleIndicators.carousel.slide.position-relative.wow.slideInLeft( data-wow-duration="1s" data-ride="carousel"  style="margin-top: 3.5rem;")
    ol.carousel-indicators
        li(data-target="#carouselExampleIndicators" data-slide-to="0" class="active")
        li(data-target="#carouselExampleIndicators" data-slide-to="1")
        li(data-target="#carouselExampleIndicators" data-slide-to="2")
    div.carousel-inner
        div.carousel-item.active.clearfix
            img.d-block.float-right.img-carousel-principal(src="http://localhost:3000/img/img1.png?auto=yes&bg=777&fg=555&text=First slide" alt="First slide")
            div.carousel-caption.d-none.d-md-block.float-left.d-inline-block.conte-titulo-index
                h1.pb-3 ¿Quieres hacer crecer tu negocio?
                p.h4.pb-3 ¡Nosotros tenemos la solución!
                a(href="#contacto").btn.botones-now.btn-empecemos-principal.hvr-grow EMPECEMOS
        div.carousel-item.clearfix
            img.d-block.float-right.img-carousel-principal(src="/img/img2.png?auto=yes&bg=666&fg=444&text=Second slide" alt="Second slide")
            div.carousel-caption.d-none.d-md-block.float-left.d-inline-block.conte-titulo-index
                h1.pb-3 Llegó el momento de crecer tu negocio
                p.h4.pb-3 ¡Resultados 100% garantizados!
                a(href="#contacto").btn.botones-now.btn-empecemos-principal.hvr-grow EMPECEMOS
        div.carousel-item.clearfix
            img.d-block.float-right.img-carousel-principal(src="/img/img3.png?auto=yes&bg=555&fg=333&text=Third slide" alt="Third slide")
            div.carousel-caption.d-none.d-md-block.float-left.d-inline-block.conte-titulo-index
                h1.pb-3 ¿Quieres hacer crecer tu negocio?
                p.h4.pb-3 ¡Nosotros tenemos la solución!
                a(href="#contacto").btn.botones-now.btn-empecemos-principal.hvr-grow EMPECEMOS
    a.carousel-control-prev(href="#carouselExampleIndicators" role="button" data-slide="prev")
        span.carousel-control-prev-icon(aria-hidden="true")
        span.sr-only Previous
    a.carousel-control-next(href="#carouselExampleIndicators" role="button" data-slide="next")
        span.carousel-control-next-icon(aria-hidden="true")
        span.sr-only Next

passport:

var passport = require('passport'),
LocalStrategy = require('passport-local').Strategy,
Usuarios = require('../models/consultora-connection').Usuarios


passport.serializeUser((usuario, done)=>{
 return done(null, usuario._id)
})

passport.deserializeUser((id, done)=>{
 Usuarios.findById(id, (err,usuario)=>{
    return done(err, usuario)
 })
})

passport.use(new LocalStrategy(

{usernameField: 'correo'},
(correo, password, done)=>{
    Usuarios.findOne({correo}, (err, usuario)=>{
        if(!usuario){
            return done(null, false, {message: `Este correo ${correo} no 
esta registrado`})
        }else{
            usuario.compararPassword(password, (err, sonIguales)=>{
                if(sonIguales){
                    return done(null, usuario)
                }else{
                    return done(null, false, {message: 'La contraseña no es 
 válida'})
                }
            })
         }
     })
  }
))


exports.estaAutenticado = (req, res, next)=>{
  if(req.isAuthenticated()){
    return next()
 }
  return res.redirect('/')
}

exports.noestaAutenticado= (req, res, next)=>{
  if(!req.isAuthenticated()){
    return next()
 }

    return res.redirect('/')

}
1 Answers

You'll get this error whenever you send a response in Express and don't immediately terminate the request. Your code keeps running and can try to send a second response after the first one has already been dispatched. I now tend to use this syntax whenever my route handlers are more than basic:

return res.render(...);

or:

res.render(...);
return;

I believe that yours is caused by defining ConsultoraModel.inicio twice, which is surely causing some strange behavior related to this. You define the function, then you call the function again passing the function body into it.

ConsultoraController.inicio = (req, res, next)=>{

    ConsultoraModel.inicio(()=>{

You should change the controller code to this:

ConsultoraController.inicio = (req, res, next)=>{

  let locals={
    title: `Now Consultora`,
    description: `El mejor lugar para encontrar de todo.`,
    keywords:"now consultora, desarrollo web, diseño publicitario, google adwords, facebook ads, asesorias",
    data:{
      sesion: (req.user) ? true : false
    }
  }

  if(!req.user){
    res.clearCookie('connect.sid', { path: '/' });
  }

  res.render('index', locals);

}
Related