Products aren't displayed after fetching data from mysql db (node.js & express)

23 views Asked by At
const express = require('express');
const router = express.Router();
const db = require('../db'); // Import MySQL connection

// Handle GET request to the root URL
router.get('/', function(req, res) {
  // Query to count the number of rows in the products table
  db.query('SELECT COUNT(*) AS productCount FROM products', (err, countResult) => {
    console.log("index.js file is being executed.");

    if (err) {
      console.error('Error counting products:', err);
      res.status(500).send('Error counting products');
    } else {
      const productCount = countResult[0].productCount; // Extract product count from the result
        if (productCount === 0) {
          console.log('No products found');
          res.render('index', {
            session: req.session,
            products: [],
            productCount: 0
          });
        }
      
      // Query to select all columns from the products table
      db.query('SELECT * FROM products', (err, results) => {
        if (err) {
          console.error('Error retrieving product data:', err);
          res.status(500).send('Error retrieving product data');
        } else {
          console.log('Products:', results);
          // Map the results to modify the image column to display only the first image filename
          const products = results.map(product => {
            // Split the images filenames using dash (-) separator
            const imageFilenames = product.images.split('-');
            // Replace dashes in filenames with colons (:)
            const sanitizedFilenames = imageFilenames.map(filename => filename.replace(/-/g, ':'));
            // Select the first filename
            const firstImage = sanitizedFilenames[0];
            // Return the modified product object
            return {
              ...product,
              // Replace the images column with the first image filename
              images: firstImage
            };
          });

          res.render('index', { 
            session: req.session,
            products: products,
            productCount: productCount
        });
        }
      });
    }
  });
});

module.exports = router;

I'm trying to fetch data from mysql database table called 'products' , I have index.hbs setup and everything should be working, I've checked all routes and I still get nothing, page should display number of products there are + images, title, stuff like that. But for some reason, there's nothing in the console, no errors, nothing at all! Is something wrong with this piece of code or should I look somewhere else?

0

There are 0 answers