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

时间:2018-09-17 16:03:20

标签: node.js express mongoose pug passport.js

确实,问题是在几次我以页面开始的会话进行导航之后开始的,并且在我将它们从会话中删除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" 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

护照:

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 个答案:

答案 0 :(得分:0)

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

extension ViewController: CAAnimationDelegate {
    func animationDidStop(_ anim: CAAnimation, finished flag: Bool) {
        someLabel.layer.mask = nil
    }
}

或:

return res.render(...);

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

res.render(...);
return;

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

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

    ConsultoraModel.inicio(()=>{