Building an e-Commerce website with Node – Part 34 – Create single product page in Node.js

Now, we have to create the single product page. When you click on a product that is displayed on the category page you have to be taken to that particularly product page.

First we have to create a new route in the main.js under the routes folder. Open the file and type in the following code.

router.get('/product/:id', function(req, res, next) {
  Product.findById({ _id: req.params.id }, function(err, product) {
    if (err) return next(err);
    res.render('main/product', {
      product: product
    });
  });
});

What this code does is that it searches for a particular id of a product and renders the product page which is located in the main folder.

We have to create the product.ejs file first, in the main folder. Type in the following code.

<% layout('layout') -%>

<div class="container">
  <div class="row">

    <div class="col-md-4">
      <img src="<%= product.image %>">
    </div>

    <div class="col-md-4">

    </div>

    <div class="col-md-4">
      <h3><%= product.name %></h3>
      <h1><%= product.price %></h1>
    </div>
  </div>
</div>

Now, when you click on a particular product on the category page you are taken to the single product page.

Leave a Reply