Folder list
Hi, I'm new to node, express and ejs; this is a folder list of my project and for some reason when I include the header and footer on home.ejs, I can see the image on the navbar, but if I do the same in terms-condition.ejs, node load the page correctly with the footer and the navbar, but the logo-image isn't shown in the page.
The only difference between home.ejs and terms-condition.ejs is that the last one is in a subfolder of /views.
index.ejs
const express = require("express");
const bodyParser = require("body-parser");
const app = express();
app.set("view engine", "ejs");
app.use(bodyParser.urlencoded({extended: true}));
app.use(express.static("public"));
app.get("/", function(req, res) {
res.render("home");
});
app.get("/legal/terms-condition", function(req, res) {
res.render("legal/terms-condition");
});
app.listen(3000, function(){
console.log("Server started on port 3000.");
});
home.ejs
<%- include("common/header") -%>
<div class="box">
Terms and Condition
</div>
<%- include("common/footer") -%>
terms-condition.ejs
<%- include("../common/header") -%>
<div class="container">
<div class="row">
<div class="col-6">
<h1>This is a sample</h1>
</div>
<div class="col-6">
<p>Why ejs not load the logo in the navbar?</p>
</div>
</div>
</div>
<%- include("../common/footer") -%>
here the link to my project on GitHub
You need to prefix the images/Stack_Overflow_icon.svg with / i.g. /images/Stack_Overflow_icon.svg. In your code, did you notice that the styles.css loading correctly because you've prefix it with /.
You're facing this issue because the file terms-condition.ejs is within a folder whereas home.ejs not.
P.S. You should always put node_modules in .gitignore file.
Related
In this problem, I tried to render ejs after update the data from UI. Here is my code,
const express = require("express");
const bodyParse = require("body-parser");
const date = require(__dirname + "/date.js");
const app = express();
const port = 3000;
app.set("view engine", "ejs");
app.use(bodyParse.urlencoded({ extends: true }));
var path = require('path');
let items = ["Buy Food", "Cook Food", "Eat Food"];
let itemWorks = [];
app.get("/", function (req, res) {
let day = date.getDay();
res.render(path.join(__dirname + "/views/list.ejs"), { listTitle: day, listItem: items });
items.pop;
app.post("/", function (req, res) {
let item = req.body.foodservice;
if(res.body.list === "work"){
itemWorks.push(item);
res.redirect("/work");
}else{
items.push(item);
res.redirect("/");
}
items.push(item);
res.redirect("/");
});
});
Here is my list.ejs:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>To Do List</title>
</head>
<body>
<h1><%=listTitle%></h1>
<ul>
<% for(var i = 0; i < listItem.length; i++){ %>
<li><%=listItem[i]%></li>
<% } %>
</ul>
<form action="/" method="post">
<input type="text" name="foodservice" placeholder="New Item" autocomplete="off"/><br /><br />
<button type="submit" name="button" value=<%=listTitle%>>+</button>
</form>
</body>
</html>
Here is my project's structure:
BRANDNEW_PROJECT views /list.ejs app.js data.js
However, when I have executed it=> errors have been displayed as bellow
TypeError: Cannot read properties of undefined (reading 'list')
at E:\WEB DEVELOPMENT\NodeJS\BrandNew_Project\app.js:25:15
I have tried to debug by putting log to check whether it already points to file that I want or not and the path is correct and also to tried set up file path like this:
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
However, the issues have not been resolved.
What can be the reason here? Thanks a lot for your help.
Live working URL : https://stackblitz.com/edit/node-dmtquz?file=index.js
Views folder is default in EJS.
Concept:
when render html pages you must take care path will start for other inside views as root
when render html pages you must take care path will start for other inside views as root.
Not render views/layouts/index use layout/index because,EJS make views (or your directory) as active directory for it.
if you want to change the directory use app.set("views", path.join(path.resolve(), < dir name >)).
Structure:
views
-------- layouts
---------------- index.ejs (this file i rendered as root)
-------- partials
-----------------footer.ejs, header.ejs etc
Hope this will clear up your problem
var express = require("express");
var app = express();
// set the view engine to ejs
// app.set("views", __dirname + "/views");
app.set("view engine", "ejs");
// use res.render to load up an ejs view file
// index page
app.get("/", function (req, res) {
res.render("layouts/index" , {
displayTitle: "items viewer",
item: ["item1", "item2"]
});
});
// about page
app.get("/about", function (req, res) {
res.render("layouts/about");
});
app.listen(8080);
console.log("Server is listening on port 8080");
<!-- root dir, views/layout/list.ejs -->
<!DOCTYPE html>
<html lang="en">
<body>
<%= displayTitle%>
<hr />
<% for (let i of items) { %>
<br />
<%= i %> <% } %>
</body>
</html>
I think you need to use path.resolve instead of path.join like this:
res.render(path.resolve(__dirname + "/views/list.ejs"), { listTitle: day, listItem: items });
You might also need to update your import of the date object at the top to use path.resolve like this:
const date = require(path.resolve(__dirname + "/date.js"));
In my code I use path.resolve anytime I use __dirname
I have deployed my node.js express app to production via a docker file, however, the images are not being rendered, and browser standard placeholder images are being rendered in-place of these.
In order for my app to render these images, is there something I am doing wrong? Is there a piece of code I need to include?
My file structure is as follows
base directory > public > icons
base directory > index.js
Relevant portion of my index.js server file
const { join } = require("path");
app.set('views', join(__dirname, 'views'));
app.use(express.static(join(__dirname, 'public')));
const port = 3000
var cookieParser = require('cookie-parser')
app.use(cookieParser())
const bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }))
app.use(cookieParser());
process.env.NODE_ENV === 'production'
app.set('view engine', 'ejs');
app.get('/',(req,res)=>{
res.render('index',{
data: 'name'
})
})
Here is the error message I get when I try to open the image file
ejs file:
<% data.countries.forEach(function(count){ %>
<div class="flex">
<div class="template">
<div class=“Country>
<img class="img" src="/icons/<%= count.icon %> " width="25" height="25" /> <%= count.name %>
</div>
<div class ="Category">
<%= count.categories.map(cat=>cat.name).join(' | ') %>
</div>
</div>
</div>
<% }); %>
Can you open the file directly by his path?
One possible answer is because inside your EJS file, your image is pointing at a URL that looks something like /icons/HK.png, but your ExpressJS public path is set to /public indeated here:
app.use(express.static(join(__dirname, 'public')));
So one possible solutions is to add a new public path for your icons set by adding this code:
app.use('/icons', express.static(join(__dirname, '/public/icons')))
local host is not loading when partials(ejs templates) are added to the pages.The page loads at first if the partials are not added.But once the partials are added the page no longer loads.Also no error is also being reported.The page keeps on loading and finally shows unable to reach the adress.
var express = require("express");
var app = express();
var bodyparser = require("body-parser");
app.use(bodyparser.urlencoded({extended: true}));
app.set("view engine", "ejs");
app.get("/", function(req , res){
res.render("landing");
});
app.get("/campgrounds", function(req,res){
res.render("campgrounds",{campgrounds:campgrounds});
});
app.post("/campgrounds",function(req,res){
var name = req.body.name;
var image = req.body.image;
var newCamp = {name: name, image:image}
campgrounds.push(newCamp)
res.redirect("/campgrounds");
});
app.get("/campgrounds/new", function(req, res){
res.render("new.ejs");
});
app.listen(3000, function(){
console.log("Yelp camp server has started");
});
when the headers are added to the the following page the page no longer loads
<%- include('partials/header.ejs') %>
<h1>landing page</h1>
view all campgrounds
<p>asdasdasda</p>
<%- include('partials/footer.ejs') %>
Please help!!!!
also here is the code for the header
<!DOCTYPE html>
<html>
<head>
<title>YELPCAMP</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" >
</head>
<body>
<p>header tabs</p>
You're missing a - from the closing tag:
<%- include('partials/header.ejs') -%>
...
<%- include('partials/footer.ejs') -%>
Thanks for the help ,
The problem was occurring because of an incorrect bootstrap cdn and the partials declaration.
Fixed those issues and the app is now working fine.
I am trying to learn node.js with the help the book "Get programming with node.js" by Jonathan Wrexler. In chapter 10 the use of partials is explained very briefly and I am not getting it to work.
I made a nav.ejs in the partials-folder that looks like this:
<ul>
<li>One</li>
<li>Two</li>
<li>Three</li>
</ul>
The layout.ejs-example in the book looks like this:
<body>
<header>Header</header>
<nav>
<% include partials/nav %>
</nav>
<%- body %>
<footer>Footer</footer>
</body>
But this gives me a syntax-error:
SyntaxError: Unexpected identifier in C:\node-projects\wandelverhalen\views\layout.ejs while compiling ejs
With the help of stackoverflow I changed the include template to:
<% include ("partials/nav"); %>
This solved the error, but it does not show the nav when I run it. And the page source shows a <nav>-tag that is empty.
I would appreciate any help.
For the sake of completeness, this is my index.js:
"use strict";
const port = 3000;
const express = require("express");
const app = express();
const homeController = require("./controllers/homeController");
const layouts = require("express-ejs-layouts");
app
.set("view engine", "ejs")
.use(
express.urlencoded({
extended: false
})
)
.use(express.json())
.use(layouts)
.use((req, res, next) => {
console.log(`Request made to ${req.url}`);
next();
})
.get("/", homeController.sendReqParam)
.get("/:myname", homeController.sendReqParam)
.listen(port, () => {
console.log(`Server is running on port ${port}`);
});
You want to use <%- include ("partials/nav"); %> to render your partial. The <% is just for scripting and control-flow and produces no output, thus you are not seeing anything added to the page. Adding a - after <% will cause it to output the unescaped value of include ("partials/nav").
I am new to node js. i am trying to learn node js. My question is how can we create dynamic webpages using node js?
PHP
<html>
<body>
<?php .......... ?>
</body>
Like in php we can do this way. How can we do in node js.
First off you would start by installing the nodejs framework expressJS
sudo npm install express
For instance, let's say you want to create a form.
<html>
<body>
<head>
This is a simple form
</head>
<body>
<form action="/" method="POST">
<label for="firstName">First Name:</label>
<input name="firstName">
<br>
<label for="lastName">Last Name:</label>
<input name="lastName">
<br>
<button type="submit">send</button>
This what the server side part would look like
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
var urlencodedParser = bodyParser.urlencoded({ extended: false});
// Set EJS View Engine**
app.set('view engine','ejs');
// Set HTML engine**
app.engine('html', require('ejs').renderFile);
//set directory
app.set('views', __dirname + '/views');
//static folder
app.use(express.static('staticfolder'));
app.get('/form', function(req, res) {
//open form.html from the views directory
res.render('form');
});
app.post('/', urlencodedParser, function(req, res) {
//retrieve first and lastname
var firstName = req.body.firstName;
var lastName = req.body.lastName;
//open submitted.html after the user has submitted the form
res.render('submitted', {output: req.body.firstName});
});
app.listen(3000);
Page that will be displayed when user submits the form. It is called submitted.html in this case
<html>
<body>
<p> you have submitted the form </p>
<!--firstname entered by user-->
<p> your first name is <%= output %></p>
</body>
</html>
You need a template to dynamically change its content.
Step 1: Create a server with Express Node.JS Framework.
Step 2: Use EJS(Embedded JavaScript) to create a template.
Follow the instructions bellow:
https://shockoe.com/ideas/development/creating-dynamic-web-pages-ejs/