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"); %>