javascript - Check for a GET variable in URL -
so i'm making simple log in form in site using jade , expressjs. it's working, problem i'm having when user enters incorrect log in details. when enter wrong details redirect them log in page parameter in url (/admin?falselogin
). question is: how can check if variable exists in jade view?
this code:
log-in.jade
form(action="/log-in" method="post") label username input(type="text" class="form-control" name="username" placeholder="username") label password input(type="text" class="form-control" name="password" placeholder="password") input(type="submit" class="btn btn-info pull-right" style="margin-top: 15px;" value="log in")
app.js
app.get("/admin",function(req, res){ if(req.session.username){ res.render("admin", {session_name: req.session.username}); }else{ res.render("log-in"); } }); app.post("/log-in", function(req, res){ var admin = admin.findone({"username": req.body.username, "password": req.body.password}); admin.count(function(error, count){ //console.log(count); if(count > 0){ req.session.username = req.body.username; res.redirect("/admin"); }else{ res.redirect("/admin?falselogin"); } }); });
i tried following inside jade view error cannot read property 'location' of undefined
:
- var page = window.location.pathname if page === "/admin?falselogin" .alert.alert-danger error! wrong details, please try again!
i come php background, in php able check directly in html using:
<?php if(isset($_get['falselogin'])){// display error user } ?>
any appreciated. thanks!
first, recommend using full key-values query string, /admin?login=false
then use req.query
specific variable , pass jade view or using res.locals
make variable accessible in views.
app.js
app.get("/admin",function(req, res){ res.locals.login = req.query.login; // accessible in view 'login' if (req.session.username) { res.render("admin", {session_name: req.session.username}); } else { res.render("log-in", { login: req.query.login, // or pass variable view directly, accessible in view 'login' }); } });
reasoning. don't think it's practice parse url query directly in view. while fine raw php example using $_get, if use mvc framework, laravel example, move away that. let controller job of handling logic based on queries , handing off relevant information views. in view, should simple presentation logic.
Comments
Post a Comment