Building an e-Commerce website with Node – Part 24 – Fixing the navigation bar

At this point we can’t navigate on the pages unless we type in the navigation bar of the browser. We are going to change that.

Open the navbar.ejs under partials folder and replace the code you have there with the following code:


<nav class="navbar navbar-inverse navbar-fixed-top">
  <div class="container">
    <div class="navbar-header">
      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
        <span class="sr-only">Toggle navigation</span>
      </button>
      <a class="navbar-brand" href="#">Project name</a>
    </div>
    <ul class="nav navbar-nav navbar-right">
      <% if (!user) { %>
      <li><a class="dropdown-toggle" data-toggle="dropdown" href="#">Signup / Login</a>
        <ul class="dropdown-menu">
          <li><a href="/signup">Signup</a></li>
          <li><a href="/login">Login</a></li>
        </ul>
      </li>
     <% } else { %>
      <li><a class="dropdown-toggle" data-toggle="dropdown" href="#"><%= user.profile.name %></a>
        <ul class="dropdown-menu">
          <li><a href="/profile">Profile</a></li>
          <li><a href="/logout">Logout</a></li>
        </ul>
      </li>
      <% } %>
    </ul>
  </div>
</nav>

Besides the HTML code there is some JavaScript code. It says that if the user is logged in then it will display its name. Normally, when you click on the user’s name you should have a drop-down menu with two options: Profile and Log out. In order to have this functionality we have to use jQuery.

The following code I copied from the http://code.jquery.com/ website and I paste it into the layout.ejs file just under the include ./partials/footer line.


      <script
        src="http://code.jquery.com/jquery-3.2.1.min.js"
			  integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
			  crossorigin="anonymous"></script>

Below this code I copied from the https://www.bootstrapcdn.com/ website the complete JavaScript link and I pasted it below the jQuery code.


<script 
src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js">
</script>

Now, the navbar should be perfectly functional.

What we want to do next is to create a logout route. Let’s open the user.js file and create the logout route. In user.js file just above the last line of code type the following code:


router.get('/logout', function(req, res, next) {
  req.logout();
  res.redirect('/');
});

Now, when you logout you should be redirected to the home page.

Leave a Reply