简体   繁体   中英

Express js - How to set variable in session?

I have a login form that ask to user, username, password and company name. The company name is the database name, so in login post request I have to set database name in session.

I think the better option is in session , right? and not in req.locals .

For example, I tried to set with req.locals but don't work:

app.js

// Global Vars
app.use(function (req, res, next) {
  res.locals.success_msg = req.flash('success_msg');
  res.locals.error_msg = req.flash('error_msg');
  res.locals.error = req.flash('error');
  res.locals.user = req.user || null;
  res.locals.database = req.database || null;
  next();
});
// Express Session
app.use(session({
    secret: 'secret',
    saveUninitialized: true,
    resave: true
}));

And in /login post route I try to set like this:

req.locals.database = 'db_xpto';

And in view I tried to show the variable but don't show nothing:

h4 Using database: #{database}

Which is the better solution to do that, local variable or session? And how can I set that?

Note: In login I'm using passport .

IMO, using a session is a better approach as it is automatically handled by the session middleware. Also res.locals is not available for the session but only for that request. You can modify your code to use session in the route directly instead of using an explicitly defined middleware.

  res.session.success_msg = req.flash('success_msg');
  res.session.error_msg = req.flash('error_msg');
  res.session.error = req.flash('error');
  res.session.user = req.user || null;
  res.session.database = req.database || null;

And you can do this in the same way in your login route as well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM