share session in expressjs

2

I want to share the session that I create on the server to a router

on the server: app.js

var routesEvaluacion = require('./routes/evaluacion');
app.use('/evaluacion', routesEvaluacion);
...
app.use(session({
    secret: 'administrador',
    resave: false,
    saveUninitialized: true
}))
app.post('/consultas', function (req, res) {

    if (req.body.nombre === "student" && req.body.pass === "student") {
        req.session.nombre = 'student';
        res.redirect('/listaEvaluaciones');
    }

});

and I need the session on the router evalcion.js

router.get('/autenticacion/:id',function (req, res) {
 // necesito la session **req.session.nombre**
});
    
asked by hubman 25.12.2017 в 23:39
source

1 answer

2
  

Credit to robertklep for his Stack Overflow answer in English .

Once you mount a router in an application in Express, any middleware declaration that occurs later in the app will not be called in requests that target that router.

For example, if you do this:

app.use(router);
app.use(session(...));

Then session will not be available in router . But it will be if you change the order:

app.use(session(...));
app.use(router);

You must mount the router (in your case evaluacion ) after defining the session and not before to solve the problem:

app.use(session({
    secret: 'administrador',
    resave: false,
    saveUninitialized: true
}))
...
app.use('/evaluacion', routesEvaluacion);
...
    
answered by 26.12.2017 / 02:55
source