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!.
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>
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>
<% }) %>
<% } %>
Here is my db.js:
const { Pool, Client } = require('pg');
const pool = new Pool({
user: "postgres",
host: "localhost",
database: "myfirst_postgres",
password: "qweqwe",
port: 5432
});
// ...
pool.query("SELECT * FROM members ",
(err, res) => {
console.log(err, res)
pool.end()
});
I want to require it in result.ejs
I wrote in result.ejs file like : <%= require ('/db.js')=%>
but after what should i write
Thanks in advance!
You can pass the results from your db-query to the ejs-template. Something like this (assuming you are using express):
Request-Handler:
app.get('/get-data', (req, res) => {
pool.query('SELECT * FROM members ', (err, res) => {
if (err) {
//handle error
}
pool.end();
res.render('result', { members: res.rows });
});
});
EJS-File result.ejs (in views folder):
<% if (members.length > 0) { %>
<div class="grid">
<% for(member of members) { %>
<p><%= member.firstName %></p>
<!-- and so on for other properties -->
<% } %>
</div>
<% } else { %>
<h3>No members found!</h3>
<% } %>
I'm building a goals app with node/express/psql. When I click on a goal on the index page, I want it to link to the show page for that goal. However, each one is linking to the goal with the id=1. I'm confused because the .forEach I use to print the objects in the first place is working, just not the link. Any help would be appreciated!
index.ejs:
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="styles.css">
<meta charset="UTF-8">
<title>Goals</title>
</head>
<body>
<h1>Here's a look at all of your goals!!</h1>
New Goal?
<% goals.forEach(goal => { %>
<div class="goal-container">
<h2><%= goal.description %></h2>
<p><%= goal.step1 %></p>
<p><%= goal.step2 %></p>
<p><%= goal.step3 %></p>
<p><%= goal.step4 %></p>
</div>
<% }) %>
</body>
</html>
controller:
const Goal = require('../models/goal');
const goalsController = {};
goalsController.index = (req, res) => {
Goal.findAll(req.user.id)
.then(goal => {
res.render('goals/', { goals: goal });
})
.catch(err => {
res.status(400).json(err);
});
};
goalsController.show = (req, res) => {
Goal.findById(req.params.id)
.then(goals => {
console.log('goals show');
res.render(`goals/show`, { goals:goals })
})
.catch(err => {
res.status(400).json(err);
});
};
module.exports = goalsController;
routes:
const express = require('express');
const goalsController = require('../controllers/goals-controllers');
const goalsRouter = express.Router();
goalsRouter.get('/', goalsController.index);
goalsRouter.get('/new', goalsController.new);
goalsRouter.get('/:id', goalsController.show);
goalsRouter.get('/:id/edit', goalsController.edit);
goalsRouter.put('/:id', goalsController.update);
goalsRouter.post('/', goalsController.create);
goalsRouter.delete('/:id', goalsController.delete);
module.exports = goalsRouter;
model:
const db = require('../db/config');
const Goal = {};
Goal.findAll = id => {
return db.query(`SELECT * FROM goals JOIN users ON goals.user_id = users.id WHERE goals.user_id = $1`, id)
};
Goal.findById = id => {
console.log('findbyId')
return db.oneOrNone(`SELECT * FROM goals WHERE id = $1`, [id])
};
module.exports = Goal;
Thanks in advance!
I believe there is something wrong with your index.ejs
Try replacing <h2><%= goal.description %></h2>
with <h2><%= goal.description %></h2>
I'm using mongoose and express along with EJS. For some reason, data I have in my mongodb is not appearing in the view. I get no errors, it's just blank.
var Person = require('.././schema.js');
module.exports = function(app) {
app.get('/about', function(req, res) {
var peopleList = [];
var title = "Users in Database:";
Person.find(function (err, people) {
if (err) return console.error(err);
for(var i = 0; i < people.length; i++) {
peopleList.push({name: people[i].name, role: people[i].role, wage: people[i].wage});
}
console.log(peopleList);
console.log(peopleList[0].name + ' ' + peopleList[0].wage + ' ' + peopleList[0].role);
});
res.render('pages/about', {
peopleList: peopleList,
title: title
});
});
}
And in my view:
<h3><%= title %></h3>
<blockquote>
<ul>
<% for(var i = 0; i < peopleList.length; i++) { %>
<li><%= peopleList[i].name %> : <%= peopleList[i].role %> : <%= peoplelist[i].wage %></li>
<% }; %>
</ul>
Alternate attempt:
<ul>
<% peopleList.forEach(function(peopleList) { %>
<li><%= peopleList.name %> - <%= peopleList.role %></li>
<% }); %>
</ul>
<%= title %> works just fine, just not the data. If I create my own array with objects in it and use the same forEach loop, it also works.
var Person = require('.././schema.js');
module.exports = function(app) {
app.get('/about', function(req, res) {
var peopleList = [];
var title = "Users in Database:";
Person.find(function (err, people) {
if (err)
return console.error(err);
for(var i = 0; i < people.length; i++)
{
peopleList.push({name: people[i].name, role: people[i].role, wage: people[i].wage});
}
console.log(peopleList);
console.log(peopleList[0].name + ' ' + peopleList[0].wage + ' ' + peopleList[0].role);
res.render('pages/about', {
peopleList: peopleList,
title: title
});
});
});
}
Please change your code to this.
Note: you should put res.render in the callback function of Person.find.