Search code examples
node.jsapiejs

why .forEach is not a function ejs api?


I have the following error:

TypeError: C:\Users\40775\Desktop\OSF Project\MyShop1\views\homepage.ejs:40
    38|     <main>
    39| 
 >> 40|             <% categories.foreach(function(category, index){ %>
    41|                <% category.page_title %>
    42|            <% }); %> 
    43| 

categories.foreach is not a function

categoryController:

const apiService = require('../services/apiService');



async function getAllCategories() {
        let result = await apiService.getAllCategoriesApi();
            return result;
}

module.exports = {
    getAllCategories: getAllCategories
  };

Here is my indexRoutes:

const categoryController = require('../controllers/categoryController');

module.exports = (app) => {

    app.get('/', async (req, res) => {
      const data = await categoryController.getAllCategories();
      res.render('homepage', {categories : data});
    });
   
    app.use(function onError(err, req, res, next) {

      res.statusCode = 500;
      res.end(err + '\n');
    });
}

Here is my homepage.ejs:

        <

% categories.foreach(function(category, index){ %>
               <% category.page_title %>
                    <% }); %> 

I have checked the API connection and it works, I'm getting my object, I will post it anyway, maybe it helps.. This is the object:

[
  {
    image: 'categories/mens-accessories-luggage.jpg',
    _id: '5e797c450d754a55dcf9f41e',
    id: 'mens-accessories-luggage',
    name: 'Luggage',
    page_description: "Shop Men's Wheeled Luggage. Versatile, rugged suitcases, baggage, holdalls and shoulder bags. All with famous long-lasting quality.",
    page_title: "Men's Wheeled Luggage",
    parent_category_id: 'mens-accessories',
    c_showInMenu: true,
    __v: 0
  }
]

Thank you guys in advice!


Solution

  • You have a syntax issue. Change foreach to forEach

    <% categories.forEach(function(category, index){ %>
      <% category.page_title %>
    <% }); %>