Question

1st Question

I'm current working on an express/jade web application and quite new to it. I've followed some tutorials and examples and put together most of the back-end and have a full stack. What I'm currently trying to do is check for if a user is currently logged in and render jade that's dependent on the outcome of that check.

I'm aware that one can natively put JavaScript in jade templates. I have a home page and would like to show a different nav-bar depending on the log-in state of the current user.

previously in my routing I was able to simply check the for this like

app.get('/', function(req, res){
    if (req.cookies.user == undefined || req.cookies.pass == undefined)

    other code...

Can the same be done in a Jade template? How would I go about this? Is this a bad approach are there easier or better ways to tackle this?

2nd Question

What I'm curious about now is, is this request object just something in the DOM I can access and check with something like Jquery?

A follow up question I have here is javascript specific. I come from a Java OO background and this is the first time I've played with JS, the fact that it's a functional language leaves me confused. For example referring to the anonymous function above as the 2nd argument to the app.get function, where is it getting req and res from? Does express/node simply hand it a request and response or how does that work?

Était-ce utile?

La solution

about 1st question, no its not a bad approach usually that kind of checking is left outside of the jade document for keeping the document in a clean state.

you can try to expose Objects to res.render which makes available the data to document. so to avoid much of the javascript code in jade template just expose a user object.

var user={loggedIn:false}

about 2nd question, req, res are passed on each time , by express using the middleware pattern, until a res.send or res.end or res.render (and other) are called which stop the execution of middleware stack.

a simple example would be

app.get("/",
 function(req,res,next){
    req.hello=world; if(next){next()};
 }
 ,function(req,res){
    res.send(200,req.hello);
 });
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top