When using forEach in the include file, no parameters are defined.
Why is the error resolved when I use "if"?
main.ejs
<% const mainList = [
{
term: 'title1',
description: 'text1'
},
{
term: 'title2',
description: 'text2'
}
] %>
<%- include('./sub', { mainList: mainList }) %>
sub.ejs
<% mainList.forEach((item) => { %>
<dl>
<dt><%= item.term %></dt>
<dd><%= item.description %></dd>
</dl>
<% }) %>
Why is the error resolved?
<% if (typeof mainList !== 'undefined') { %> // Why is the error resolved?
<% mainList.forEach((item) => { %>
<dl>
<dt><%= item.term %></dt>
<dd><%= item.description %></dd>
</dl>
<% }) %>
<% } %>
Related
your text <%= post.user.name %> show TypeError in ejs file
this is my post_controller:-
this is error show in web page
const Post = require('../models/post'); module.exports.home = function (req, res) {
// populate the user of each post
Post.find({}).populate('user').exec(function (err, posts) {
return res.render ('home', {
title: "Home",
posts: posts
});
})
}
This is my home.ejs file part:-
<ul>
<% for(post of posts){ %>
<li>
<%= post.content %>
<br>
<%= post.user.name %>
</li>
<% } %>
</ul>
I have a ejs like this
<!DOCTYPE html>
<html lang="en">
<head>
<%- include('../partials/head'); %>
</head>
<body class="container">
<header>
<%- include('../partials/header'); %>
</header>
<main>
<div class="jumbotron">
<h1>This is great</h1>
<p>Welcome to templating using EJS</p>
<% rows.forEach(function (rows) { %>
<tr>
<td><%= rows.tag %>
<div>
<%
var contents = egallery.getContents(rows.tag)
%>
<%= JSON.stringify(contents) %>
</div>
</td>
</tr>
<% }) %>
</div>
</main>
<footer>
<%- include('../partials/footer'); %>
</footer>
</body>
</html>
and a custom js calling mysql and return data
var conn = require('./conn.js');
conn.connect();
function getTags () {
return new Promise((resolve, reject) => {
conn.query(
"Select distinct tag from ray_url",
(err, result) => {
if (err) {
console.log(err);
throw err;
}
return err ? reject(err) : resolve(result)
}
)
})
/*conn.end();*/
}
function getContents (tag) {
return new Promise((resolve, reject) => {
conn.query(
"Select * from ray_url where tag = ?",
[tag],
(err, result) => {
//if (err) {
console.log(result); //i saw data
console.log(err);
//throw err;
//}
return err ? reject(err) : resolve(result)
}
)
})
}
module.exports = {
getTags : getTags,
getContents : getContents
};
i saw the data was printed, but the line var contents = egallery.getContents(rows.tag) , the contents is blank, any one know what is the problem?
I'm creating facebook like social media app using nodejs and ejs. I'm getting error " Cannot read property 'contentType' of undefined". But I get this error on profile.ejs and not on newsfeed.ejs. profile.ejs render photo if there's photo in the post but if I post a post with text only,this "Cannot read property 'contentType' of undefined" error occur.
app.js
app.get("/newsfeed", function(req, res){
if(req.isAuthenticated()){
Post.find({}, function(err, foundItem){
if(err){
console.log(err);
} else {
const loggedUser = req.user;
res.render("newsfeed", {posts: foundItem, loggedUser: loggedUser, foundUser: "undefined"});
}
}).sort({date: -1});
} else {
res.redirect("/login");
}
});
app.get("/profile/:userProfile", function (req, res) {
const userId = req.params.userProfile;
const loggedUser = req.user
if(req.isAuthenticated){
User.findById(userId, function(err, foundUser){
if(err){
console.log(err);
} else {
res.render("profile", {foundUser: foundUser, loggedUser:loggedUser});
}
}).sort({date: -1});
}
})
newsfeed.ejs
<% posts.forEach( function(post) { %>
<div class="post">
<!-- Post contents -->
<%= post.name %>
<p class="date"><%= post.date %></p>
<p class="content"><%= post.content %></p>
<% if(post.img != "undefined") { %>
<div class="mediaFiles">
<div class="imageOverlay"><i class="fas fa-times"></i></div>
<img src="data:image/<%=post.img.contentType%>;base64,
<%=post.img.data%>" class="image" onerror="this.style.display='none'">
</div>
<% } %>
<hr>
<% }); %>
profile.ejs
<% foundUser.post.forEach( function(post) { %>
<div class="post">
<!-- Post contents -->
<%= post.name %>
<p class="date"><%= post.date %></p>
<p class="content"><%= post.content %></p>
<% if(post.img != "undefined" || post.img != null || post.img != "") { %>
<div class="mediaFiles">
<div class="imageOverlay"><i class="fas fa-times"></i></div>
<img src="data:image/<%=post.img.contentType%>;base64,
<%=post.img.data%>" class="image" onerror="this.style.display='none'">
</div>
<% } else { %>
<div class="imageOverlay"><i class="fas fa-times"></i></div>
<img src="#" class="image" onerror="this.style.display='none'">
</div>
<% } %>
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!
You have a syntax issue. Change foreach to forEach
<% categories.forEach(function(category, index){ %>
<% category.page_title %>
<% }); %>
You have missed an equal sign in <% category.page_title %>. In addition to the above answer use <%= category.page_title %>. Hurray, enjoy your coding!.
I am trying to implement the update route into a poker site I am building. I have been able to get the players to appear on the show page but I would like to update the mongo DB from inTournament: "Yes" to inTournament: "No" when the Eliminate button is selected for that player. I have included my code below. Thank you, in advance, for any help with this.
======================= app.js UPDATE ROUTE=======================
app.get("/seating", function(req, res){
//Get all players from poker_DB
Seat.find({inTournament: "Yes"}, function(err, allseats){
if(err){
console.log(err);
} else {
shuffle(allseats);
res.render("seating", {seats: allseats});
}
});
});
//Update player's tournament status
app.put("/seating", function(req, res){
Seat.findByIdAndUpdate(req.params.id, req.params.inTournament, function(err, updatedStatus){
if(err) {
console.log(err);
} else {
res.send("Data Updated");
}
});
});
======================= SHOW PAGE=======================
<div class ="row text-left" style="display:flex; flex-wrap: wrap;">
<div class="col-md-4 table table-bordered">
<h3 class="text-center">Table 1</h3>
<ol>
<% var i = 1; %>
<% var j = 0; %>
<% seats.forEach(function(seat){ %>
<% if(seat.player && i < perTable1){ %>
<% console.log(perTable2); %>
<li><%= seats[j].player %>
<form action"/seating?_method=PUT" method="POST">
<button class="btn btn-sm btn-warning" type="Submit">Eliminate</button>
</form>
</li>
<% i++ %>
<% j++ %>
<% } else { %>
<% j++ %>
<% } %>
<% return j; %>
<% }); %>
</ol>
</div>
</div>