简体   繁体   中英

Dynamic login/logout in Navbar

I'm trying to display text in the navbar that says LOGIN or LOGOUT depending on the user status, I try to use ejs engine, but it didn't work.

It shows login is not defined.

In my app.js:

    app.get("/logout", function (req, res) {
  req.logout();
  res.redirect("/");
});

app.post("/register", function (req, res) {

  User.register({ username: req.body.username }, req.body.password, function (err, user) {
    if (err) {
      console.log(err);
      res.redirect("/register");
    } else {
      passport.authenticate("local")(req, res, function () {
        res.redirect("/secrets");
      });
    }
  });

});

app.post("/login", function (req, res) {

  const user = new User({
    username: req.body.username,
    password: req.body.password
  });

  req.login(user, function (err) {
    if (err) {
      console.log(err);
    } else {
      passport.authenticate("local")(req, res, function () {
        res.redirect("/secrets");
      });
    }
  });

});

My header.ejs:

<ul class="nav navbar-nav navbar-right">
        <li id="home"><a href="/">HOME</a></li>
        <li id="register"><a href="/register">REGISTER</a></li>
          <% if (login) { %>
        <li> <a href="/logout">Logout</a></li>
          <% } else { %>
        <li><a href="/login">Login</a></li>
          % }%>
</ul>

error: login is not defined

It seems iike you have not passed the variable to the ejs template. To access a variable in the ejs you need to pass it from the server while rendering the ejs template.

This would look like this

app.get("/", function(req, res){
    res.render("header", {login: 'SOME VALUE' })
});

You might want to look at the following article to look a working example. https://dzone.com/articles/nodejs-tutorial-for-beginners-part-3-transferring

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