错误:在我初始化会话后发送标头后无法设置标头

Posted

技术标签:

【中文标题】错误:在我初始化会话后发送标头后无法设置标头【英文标题】:Error: Can't set headers after they are sent after I have initialized a session 【发布时间】:2019-02-21 14:47:40 【问题描述】:

问题确实是在我使用页面启动的会话导航几次后开始的,并且在我从会话中删除 cookie 之前,在发送它们之后给我错误无法标头。 这个错误我已经有好几天了,到目前为止我不知道出了什么问题。

型号:

'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()

控制器:

'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)
    )

路由器:

'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)

索引:

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" )
            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" )
            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" )
            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

护照:

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】:

每当您在 Express 中发送响应并且不立即终止请求时,您都会收到此错误消息。您的代码会继续运行,并且可以在第一个响应已经发送后尝试发送第二个响应。我现在倾向于在我的路由处理程序不仅仅是基本的时候使用这种语法:

return res.render(...);

或:

res.render(...);
return;

我相信您的问题是由两次定义 ConsultoraModel.inicio 引起的,这肯定会导致一些与此相关的奇怪行为。您定义函数,然后再次调用该函数,将函数体传递给它。

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

    ConsultoraModel.inicio(()=>

您应该将控制器代码更改为:

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);


【讨论】:

那么请返回并使用这些详细信息以及您收到的错误来编辑您的问题。

以上是关于错误:在我初始化会话后发送标头后无法设置标头的主要内容,如果未能解决你的问题,请参考以下文章

为啥显示此错误?发送到客户端后无法设置标头

UnhandledPromiseRejectionWarning:错误:发送后无法设置标头[重复]

异步发送错误后无法设置标头

不断收到错误:发送后无法设置标头

仅在 Cloud9 上出现错误“发送后无法设置标头”

res.send 发送后无法设置标头