novice res.locals and can not set headers after they are sent

0

Hi, I'm in need of help with a pretty strange problem I have a layout that contains the head of my html plus the navbar or navigation bar, in this navigation bar I have a form that has a select tag and these options are created with a variable that is in res.locals with an arrangement that I bring from a table in a mysql database, the information is passed with a middleware called control-sessions and what it does is pass the user information in each view within the routes localhost: 3000 / admin through res.locals and between you information I also pass the arrangement for the options of my select

the problem is the following I have a url that is / admin / upcoming-events in this url the whole layout works great the form select works and has all the options of the arrangement the problem is when I try to make another view in the url / admin / next-events / info /: idEvento and there are two errors, one is that it tells me that the variables that were defined in res .locals are undefined, variables that work perfectly in the previous url, and I already checked that the middleware if it is running, I've even sent a console.log (res.locals) and I check that the variables contain all the information I need, the other error that I get is that the console says error: can not set headers after they are sent

I want to know why the variables defined in res.locals work perfectly in one url and in the other url it does not work.

Here is my control middleware-sessions code

module.exports=function (req,res,next) {
if(!req.session.admin.id){
    res.locals = {errorLogin: true, mensajeError: "No puede acceder a esta direccion, antes debe Iniciar Sesion"};
    res.redirect("/index/login-admin");
}
else{
        res.locals = {errorEvento: true, mensajeError: "lo sentimos, hay problemas con la conexion, intenlo mas tarde, si el problema persiste contactenos"};

    var q="SELECT id_admin, permisos, habilitado, nombre_admin, correo FROM administradores WHERE id_admin='"+req.session.admin.id+"'";
    conexion.query(q, function(error, usuario, fields){
        if (!!error) {
            console.log("error encontrando la cuenta del usuario");
            console.log(error);
            res.locals = {errorLogin: true, mensajeError: "lo sentimos, hay problemas con la conexion, intenlo mas tarde, si el problema persiste contactenos"};
            res.redirect("/index/login-admin");
            return;
        }
        //console.log(usuario[0]);
            //console.log(res.locals.admin);
        q="SELECT id_escenario, nombre FROM escenarios ORDER BY nombre ASC";
        conexion.query(q,function(error4, rowsEscenarios, fields3){
            if (!!error4) {
                console.log("error en la consulta 4");
                return;
            }
            //console.log(rowsEscenarios);
                //console.log(res.locals.escenarios);
            q="SELECT id_deporte, deporte FROM deportes ORDER BY deporte ASC";
            conexion.query(q,function(error5, rowsIdDeportes, fields3){
                if (!!error5) {
                    console.log("error en la consulta 5");
                    return;
                }
                //console.log(rowsIdDeportes);
                    //console.log(res.locals.idDeportes);
                q="SELECT * FROM categoria_edad";
                conexion.query(q,function(error6, rowsCategoriaEdad, fields3){
                    if (!!error6) {
                        console.log("error en la consulta 6");
                        return;
                    }
                    //console.log(rowsCategoriaEdad);
                    console.log("middleware control-sesiones");
                    res.locals = {admin: usuario[0], escenarios: rowsEscenarios, idDeportes: rowsIdDeportes, categoriaEdad: rowsCategoriaEdad};
                    console.log(res.locals);
                });
            });
        });
    });

  }
  next();
}

the following is the jade code of the layout that I use in all the / admin url

.item_form.col-xs-12.col-md-6.col-sm-6
            label.l-t-d.col-xs-12(for="deporte") Deporte o Diciplina
            select#deporte.col-xs-12(name="deporte" form="form-nuevo-evento" -required)
                option seleccione un deporte
                - console.log(admin + " proband");
                each deporte in idDeportes
                    option(value="#{deporte.id_deporte}")=deporte.deporte

        .item_form.col-xs-12.col-sm-6
            label.l-t-d.col-xs-12(for="categoria-edad") Categoria Edad
            select#categoria-edad.col-xs-12(name="categoria_edad" form="form-nuevo-evento" -required)
                option Selecione una  
                for categoria in categoriaEdad
                    option(value="#{categoria.id_categoria_edad}")=categoria.nombre_categoria_edad             




        .item_form.col-xs-12
            label.l-t-d.col-xs-12(for="escenario") Escenario
            select#escenario.col-xs-12(name="escenario" form="form-nuevo-evento" required)
                option seleccione una esecenario
                for escenario in escenarios
                    option(value="#{escenario.id_escenario}")=escenario.nombre

these are information and errors that come out of the console

    
asked by Daniel Enrique Rodriguez Caste 12.12.2016 в 05:05
source

1 answer

1

Your problem is that next() is outside the query callback. Therefore, when the query ends the next() is already executed, then you would be doing res.locals = ... when in reality the middleware has already finished executing, and if for that moment, the endpoint made the res.send() , it will throw you that you can not modify the res once the res.send() has already been made.

If you think about it correctly, the error means that "We can not modify the answer once the response has been sent". Therefore, you are saying that you have already sent the response to the browser / client, and you are still trying to modify the response.

Solution: Put the next () inside the callback of the query in the corresponding places:

module.exports=function (req,res,next) {

    if(!req.session.admin.id){
        res.locals = {errorLogin: true, mensajeError: "No puede acceder a esta direccion, antes debe Iniciar Sesion"};
        // Usa el return, así no ejecuta el else y no hace falta tampoco
        return res.redirect("/index/login-admin");
    }


    res.locals = {errorEvento: true, mensajeError: "lo sentimos, hay problemas con la conexion, intenlo mas tarde, si el problema persiste contactenos"};

    var q="SELECT id_admin, permisos, habilitado, nombre_admin, correo FROM administradores WHERE id_admin='"+req.session.admin.id+"'";

    conexion.query(q, function(error, usuario, fields){

        if (!!error) {
            console.log("error encontrando la cuenta del usuario");
            console.log(error);
            res.locals = {errorLogin: true, mensajeError: "lo sentimos, hay problemas con la conexion, intenlo mas tarde, si el problema persiste contactenos"};
            res.redirect("/index/login-admin");
            return;
        }

        q="SELECT id_escenario, nombre FROM escenarios ORDER BY nombre ASC";

        conexion.query(q,function(error4, rowsEscenarios, fields3){
            if (!!error4) {
                console.log("error en la consulta 4");
                // Que continue el request
                next();
                return;
            }


            q="SELECT id_deporte, deporte FROM deportes ORDER BY deporte ASC";
            conexion.query(q,function(error5, rowsIdDeportes, fields3){
                if (!!error5) {
                    console.log("error en la consulta 5");
                    // Que continue el request
                    next();
                    return;
                }

                q="SELECT * FROM categoria_edad";
                conexion.query(q,function(error6, rowsCategoriaEdad, fields3){
                    if (!!error6) {
                        console.log("error en la consulta 6");
                        // Que continue el request
                        next();
                        return;
                    }

                    //console.log(rowsCategoriaEdad);
                    console.log("middleware control-sesiones");
                    res.locals = {admin: usuario[0], escenarios: rowsEscenarios, idDeportes: rowsIdDeportes, categoriaEdad: rowsCategoriaEdad};
                    console.log(res.locals);

                    // Que continue el request
                    next();
                });
            });
        });
    });
}

If you try to tweak the code a bit more, and do not use numbers in the variables. Try not to have callback hell .

    
answered by 21.01.2017 / 02:51
source