javascript - Best way for checking if a user is logged with node.js and express and change client-side html -
i'm doing web application node.js , express; i'm using sessions mongodb. server side code this:
exports.home = function(req, res){ if(req.session.userenabled){ console.log("logged"); res.render('home', { title: 'my title' , css: '/stylesheets/home.css',authenticated:'true'}); } else{ console.log("not logged"); res.render('home', { title: 'my title' , css: '/stylesheets/home.css', authenticated:'false'}); }
};
into front end check value 'authenticated' showing different html:
script. if(#{authenticated}) document.write("<div id='profile' class='myclass' ><p>show profile<p></div>"); else document.write("<div id='register' class='myclass' ><p>register<p>");
it works, question is: way giving dinamism front end pages?
i tried create function client side checking if authenticated:
function checkiflogged(){ $.get( '/checkiflogged' , function(data) { alert('result checkiflogged: '+data); return(data); });
}
calling html:
script. var authenticated=checkiflogged(); ... ... ... script. if(authenticated) document.write("<div id='profile' class='myclass' ><p>show profile<p></div>"); else document.write("<div id='register' class='myclass' ><p>register<p>");
but asinchronous result returns after page loaded 'false' value of var authenticated.
in way thought avoid check , pass value server side every res.render, doesn't work. first solution right way or second way near find better way doing that?
you may try this:
function checkiflogged(callback){ $.get( '/checkiflogged' , function(data) { alert('result checkiflogged: '+data); callback(data); }); }
and
script. checkiflogged(function(authenticated) { if(authenticated) //i wouldn't use document.write here it's bit dangerous asynchronous call document.write("<div id='profile' class='myclass' ><p>show profile<p></div>"); else document.write("<div id='register' class='myclass' ><p>register<p>"); });
Comments
Post a Comment