1

I got an error while looping the array through forEach loop in ejs file of express js. According to my research, in the ejs file forEach loop is not working. Please check the error and the message below:

Error

SyntaxError: Unexpected token ')' in E:\portfolio\views\home.ejs while compiling ejs

If the above error is not helpful, you may want to try EJS-Lint:
https://github.com/RyanZim/EJS-Lint
Or, if you meant to create an async function, pass `async: true` as an option.
    at new Function (<anonymous>)
    at Template.compile (E:\portfolio\node_modules\ejs\lib\ejs.js:673:12)
    at Object.compile (E:\portfolio\node_modules\ejs\lib\ejs.js:398:16)
    at handleCache (E:\portfolio\node_modules\ejs\lib\ejs.js:235:18)
    at tryHandleCache (E:\portfolio\node_modules\ejs\lib\ejs.js:274:16)
    at View.exports.renderFile [as engine] (E:\portfolio\node_modules\ejs\lib\ejs.js:491:10)
    at View.render (E:\portfolio\node_modules\express\lib\view.js:135:8)
    at tryRender (E:\portfolio\node_modules\express\lib\application.js:640:10)
    at Function.render (E:\portfolio\node_modules\express\lib\application.js:592:3)
    at ServerResponse.render (E:\portfolio\node_modules\express\lib\response.js:1017:7)

The code

/index.js from the root directory:

require("dotenv").config();
const express = require("express");
const path = require("path");
const PostsRoute = require("./routers/posts");
const PageRoute = require("./routers/pageRoutes/routes");
const app = express();


**MongoDB connection Here**


app.use(express.json());
app.use(express.urlencoded({extended : false}));
app.set('views', path.join(__dirname, './views'))
app.set('view engine','ejs');
app.use("/css" , express.static(path.resolve(__dirname, 'views/css')));
app.use("/js" , express.static(path.resolve(__dirname, 'views/js')));


app.use("/api",PostsRoute);
app.use("/",PageRoute);

app.listen(process.env.PORT,() => {
    console.log(`Your port is running`);
});

routers/post.js from the root directory:

const express = require("express");
const PostsRoute = require("express").Router();
const PostModel = require("../models/post");

PostsRoute.get("/posts", async (req, res) => {
  const posts = await PostModel.find();
  try {
    const result = await PostModel.find();
    res.status(200).send(result);
  } catch (error) {
    res.status(404).json({ message: error.message });
  }
});


module.exports = PostsRoute;

routers/pageRoutes/routes.js from the root directory:

const PageRoute = require("express").Router();
const axios = require("axios");

PageRoute.get("/", async (req, res) => {
  try {
    const response = await axios("http://localhost:5000/api/posts");
    res.render("home" , { posts : response.data });
  } catch (error) {
    console.log(error.message);
  }
});


module.exports = PageRoute;

Now finally the ejs file is here views/home.ejs from the root directory

<%- include("partials/header.ejs"); %>
<div class="posts container">
  <div class="row">
    <%- posts.forEach(post => { %> 
       <%- include("Postcard.ejs"); %>
    <%- }); %>
  </div>
</div>
<%- include("partials/footer.ejs"); %>
HamzaKhalid273
  • 355
  • 1
  • 4
  • 11

2 Answers2

1

you need to change this:

<%- posts.forEach(post => { %> 
   <%- include("Postcard.ejs"); %>
<%- }); %>

to this:

<% posts.forEach(post => { %> 
   <%- include("Postcard.ejs"); %>
<% }); %>

just needed to remove the -

this is from ejs docs:

<ul>
  <% users.forEach(function(user){ %>
    <%- include('user/show', {user: user}); %>
  <% }); %>
</ul>

ejs docs , scroll down to Includes title.

Elna Haim
  • 545
  • 1
  • 5
  • 19
  • Does not work but infect browser has printed it as it is with this error : posts.forEach is not a function at eval ("E:\\portfolio\\views\\home.ejs":12:14) – HamzaKhalid273 May 25 '22 at 23:19
  • Now you are facing different issue. seems like posts is not an array. can you console log the response.data before rendering the home page? just to make sure. – Elna Haim May 25 '22 at 23:23
  • Yes i have tried it in the routers/pageRoutes/routes.js file before sending the response it shows all the data to be displayed perfectly!! i don't think the error is in that file because i have also tried to print `posts[0].key` and `posts[1].key` and that is displaying the result. Most likely to have the issue with loop. Let me tell you one thing more i also have tried to use `for loop` but it is also not working. – HamzaKhalid273 May 25 '22 at 23:30
  • This is weird. it should loop through the array. its hard to debug such an issue without being able to reproduce the error.. – Elna Haim May 25 '22 at 23:46
  • OMG!! There might be another suggestion!!! – HamzaKhalid273 May 25 '22 at 23:55
-1

Unexcepted token error means, probably you can wrong use symbols like used two less than symbols << or you can not use on html "<" you must use html entity (&ls;). Just focus on symbols.

  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Oct 24 '22 at 00:28