javascript - Node.js detect if a variable exists in req for every page a user goes to -



javascript - Node.js detect if a variable exists in req for every page a user goes to -

more specifically, have auth scheme uses passportjs , req.user defined if user authenticated.

right website has 5 pages, it's growing, , @ top of every route, check if req.user exists , pass true or false variable rendered template, , template renders accordingly.

i messed around things such app.get("*") didn't end finding good.

how check if req.user (or else exist within req...) exists -- when user goes page of website, without repeting code?

progress:

using code in app.js:

app.use(function (req, res, next) { // using req.locals.isauthenticated better, it's automatically passed every rendered templates. req.context = {}; req.context.isloggedin = req.isauthenticated(); // req.locals.isauthenticated = req.isauthenticated(); next(); }); app.use('/dashboard', dashboard);

and in routes/dashboard route:

router.get('/', function (req, res) { res.render('dashboard', { isloggedin: req.context.isloggedin }); });

works - can see if user logged in doing illustration {{ isloggedin }}.

however when uncomment req.locals line in first code snippet, 500 error.

two things note:

usually when application needs bunch of different pages, want setup middleware function via app.use

express has res.locals variable properties included in rendered template

with above points in mind, can build following:

app.use(function(res, req, next) { res.locals.isauthenticated = typeof(req.user) !== 'undefined'; next(); });

you supply additional template variables when routes phone call res.render. example:

app.get('/about', function(res, req) { res.render('about', { 'testvalue': 14} ); });

your template have access both isauthenticated , testvalue.

javascript node.js

Comments

Popular posts from this blog

php - Android app custom user registration and login with cookie using facebook sdk -

django - Access session in user model .save() -

php - .htaccess Multiple Rewrite Rules / Prioritizing -