Building an e-Commerce website with Node – Part 33 – Create category page in Node.js

First we have to create a file named category.ejs under the views/main folder. When you select a category, the products belonging to that particularly category will be displayed on the category.ejs page.

Create the category.ejs file and type the following code in it.

<% layout('layout') -%>
<div class="container">
  <div class="row">
    <% for (var i = 0; i < products.length; i++) { %>
    <div class="col-md-4">
      <a href="/product/<%= products[i]._id %>">
        <div class="thumbnail">
          <img src="<%= products[i].image %>">
          <div class="caption">
            <h3><%= products[i].name %></h3>
            <p><%= products[i] %></h3>
            <p>$<%= products[i].price %></p>
    <% } %>

In the main.js file under the routes folder you have to require User and Product. When I tried to test the above created page I got the message “Product is not defined”.

var User = require('../models/user');
var Product = require('../models/product');

In order to test the category.ejs page you have to go first to your mLab database, select one of the categories and copy the id. The id, in my case, of the books category is “59728461888ece132f82a646”.

Open a browser and go to http://localhost:3000/products/59728461888ece132f82a646. The page should be populated with products belonging to the books category.

The only problem right now is that we have products only for books category. We have created the gadgets category as well but no products are displayed if we navigate to it.

To solve it you have to open your “Postman”, select the GET method and go to localhost:3000/api/gadgets then press “Send”. Once you get the message success you can go back to the browser and navigate to the category gadgets as well.

Leave a Reply