JSDOM not loading EJS pages in Node - node.js

I tried to load an EJS page using JSDOM however, I can't seem to load the page.
Here's part of my script in app.js:
const { JSDOM } = require("JSDOM");
const dom = new JSDOM('<!DOCTYPE html><p>Hello world</p>');
console.log(dom.window.document.querySelector("p").textContent); // "Hello world"
const list_dom = new JSDOM('views/list.ejs');
console.log(list_dom.window.document);
The first console log is just to make sure that I'm getting JSDOM to work.
Here's the result:
Hello world
Document { location: [Getter/Setter] }
I've tried variations of "views/list", and "views/list.ejs".
Here's my list.ejs:
<%- include('partials/header') -%>
<div class="box" id="heading">
<h1><%=listTitle%></h1>
</div>
<div class="box">
<% newListItems.forEach(function(item){ %>
<form action="/delete" method="post">
<div class="item" contenteditable="true">
<input type="checkbox" name="checkedItem" value="<%=item._id%>" onChange="this.form.submit()">
<p><%=item.name%></p>
</div>
<input type="hidden" name="listName" value="<%=listTitle%>"></input>
</form>
<% }); %>
<form class="item" action="/list" method="post">
<input type="text" name="newItem" placeholder="New Item" pattern="[a-zA-Z][a-zA-Z0-9\s]*" autocomplete="off" required autofocus>
<button type="submit" name="list" value=<%=listTitle%>>+</button>
</form>
</div>
<%- include('partials/footer') -%>

Related

Why is my ejs outputting the actual html code and not rendering it as html?

I am doing some simple validation on a form and using bootstrap for alert dismissing. I have an ejs partial for displaying error messages. When trying to render the error message its just showing the actual block of code.
Here is my partials ejs:
<% if(typeof errors != 'undefined') { %>
<% errors.forEach(error => { %>
<div class="alert alert-warning alert-dismissible fade show" role="alert">
<%= error.msg %>
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>
<% }) %>
<% } %>
Here is where I include that partial to the register.ejs file I have
<%= include ("./partials/messages") %>
<form action="/users/register" method="POST">
<div class="form-group">
<label for="name">Name</label>
<input
type="name"
id="name"
name="name"
class="form-control"
placeholder="Enter Name"
value="<%= typeof name != 'undefined' ? name : '' %>"
/>
Here is a screenshot of what it is outputting:
Why is it showing the actual code instead of rendering as HTML?

CastError: Cast to ObjectId failed for value \"undefined\" (type string) at path \"_id\" for model \"students\""

So I have a problem in my CRUD application using Node JS, Express, and Mongo DB. Actually, I am just following this tutorial but I get stuck on the UPDATE part. I am able to CREATE, READ, and DELETE values from database already, but I don't know why I keep getting this error whenever I try to UPDATE my data.
I found the error is from my controller.js file and here's the code:
exports.update = (req,res)=>{
if(!req.body){
return res
.status(400)
.send({message:"Record to be updated can not be empty!"})
}
const id = req.params.id;
studentDb.findByIdAndUpdate(id,req.body,{userFindAndModify:false})
.then(data=>{
if(!data){
res.status(404).send({message:`Cannot update student record with ID ${id}. Maybe record not found.`})
}else{
res.send(data)
}
})
.catch(err=>{
res.status(500).send({message:`Error in updating student record with id=${id}.` + err})
})
}
My hypothesis is that the objectID goes on the first model in my schema because whenever I check the console when I run the application, the last value of the model in my schema, the "contact" goes undefined.
The ERROR:
I can provide the other codes related to this if my question is still unclear. Thank you in advance for answering! I've been stuck here for hours already.
EDIT
Here's the additional front-end code
(this is the FORM part from my update_student.ejs where I update the data):
<!-- form handling -->
<form method="POST" id="update_student">
<div class="new_student">
<div class="form-group">
<div class="row">
<div class="col-lg-4">
<label for="firstName" class="text-muted">First Name</label><br>
<input type="hidden" name="id" value="<%=students._id%>">
<input type="text" name="firstName" value="<%=students.firstName%>" placeholder="Corki">
</div>
<div class="col-lg-4">
<label for="middleName" class="text-muted">Middle Name</label><br>
<input type="text" name="middleName" value="<%=students.middleName%>" placeholder="Vi">
</div>
<div class="col-lg-4">
<label for="lastName" class="text-muted">Last Name</label><br>
<input type="text" name="lastName" value="<%=students.lastName%>" placeholder="Fortune">
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-sm-4">
<label for="gender" class="text-muted">Gender</label><br>
<div class="radio inline">
<input type="radio" id="radio-2" name="gender" value="Male" <% if(students.gender == "Male"){ %>checked <% } %>>
<label for="radio-2" class="radio-label">Male</label>
</div>
<div class="radio inline">
<input type="radio"id="radio-3" name="gender" value="Female" <% if(students.gender == "Female"){ %>checked <% } %>>
<label for="radio-3" class="radio-label">Female</label>
</div>
</div>
<div class="col-md-8">
<div class="form-group">
<label for="birthday" class="text-muted">Birthday</label>
<input type="text" name="birthday" value="<%=students.birthday%>" placeholder="MM/DD/YYYY">
</div>
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-md-6">
<label for="program" class="text-muted">Program</label>
<input type="text" name="program" value="<%=students.program%>" placeholder="i.e. BSIT">
</div>
<div class="col-md-6">
<label for="yearLevel" class="text-muted">Year Level</label>
<select class="form-select" name="yearLevel">
<option value="">Select year level</option>
<option <% if(students.yearLevel == "First Year"){ %>selected <% } %> value="First Year">First Year</option>
<option <% if(students.yearLevel == "Second Year"){ %>selected <% } %> value="Second Year">Second Year</option>
<option <% if(students.yearLevel == "Third Year"){ %>selected <% } %> value="Third Year">Third Year</option>
<option <% if(students.yearLevel == "Fourth Year"){ %>selected <% } %> value="Fourth Year">Fourth Year</option>
<option <% if(students.yearLevel == "Fifth Year"){ %>selected <% } %> value="Fifth Year">Fifth Year</option>
<option <% if(students.yearLevel == "Masteral"){ %>selected <% } %> value="Masteral">Masteral</option>
</select>
</div>
</div>
</div>
<div class="form-group">
<label for="email" class="text-muted">Email</label>
<input type="text" name="email" value="<%=students.email%>" placeholder="example#gmail.com">
</div>
<div class="form-group">
<label for="address" class="text-muted">Address</label>
<input type="text" name="address" value="<%=students.address%>" placeholder="Household No., Barangay, City, Province">
</div>
<div class="form-group">
<label for="contact" class="text-muted">Contact</label>
<input type="text" name="contact" value="<%=students.contact%>" placeholder="i.e 09XX-XXX-XXXX">
</div>
<div class="form-group">
<button type="submit" class="btn text-dark update">Save</button>
</div>
</div>
</form>
<!-- form handling -->
Code for my #update_student JS just in case:
$('#update_student').on("submit",(function(event){
event.preventDefault();
var unindexed_array = $(this).serializeArray();
var data = {}
$.map(unindexed_array,function(n,i){
data[n['firstName']] = n['value']
})
console.log(data);
var request={
"url": `http://localhost:1485/api/students/${data.id}`,
"method":"PUT",
"data" : data
}
$.ajax(request).done(function(response){
alert("Data updated successfully!");
})
}))
Thanks to Sir #Rajdeep Debnath 's help, I was able to look into may "unindexed_array" from my console.log and figured out that instead of data[n['firstName']] = n['value']
I should write data[n['name']] = n['value']
I wrote the former because I thought it is just the name of the variable but in actuality, it is like the "id" or "class" called in JavaScript. The form used "name" on the inputs (like <input type="text" name="program" value="<%=students.program%>" placeholder="i.e. BSIT"> from my code) so that's why it is the one called in the function instead.
Now my code for my #update_student JS goes like this:
$('#update_student').on("submit",(function(event){
event.preventDefault();
var unindexed_array = $(this).serializeArray();
var data = {}
$.map(unindexed_array,function(n,i){
data[n['name']] = n['value']
})
console.log(data);
var request={
"url": `http://localhost:1485/api/students/${data.id}`,
"method":"PUT",
"data" : data
}
$.ajax(request).done(function(response){
alert("Data updated successfully!");
})
}))
You just simply change your Url path with ``symbol instead of ''.
Just like that
var request={
"url": `http://localhost:1485/api/students/${data.id}`,
"method":"PUT",
"data" : data
}

put route not working in node.js showing error cannot PUT

put route is not working in the following code . I have installed method-override too . I can't find the error in my code .this is the error I am getting : Cannot PUT /blogs/5dc41f2e1c5eb907574a24db
//UPDATE route
app.put("/blog/:id", function(req, res) {
Blog.findByIdAndUpdate(req.params.id, req.body.blog, function(err, updatedBlog) {
if(err) {
res.send("ERROR!");
} else {
res.redirect("/blogs/"+req.params.id);
}
});
});
// FORM
<% include ./partials/header %>
<div class="container form_container">
<h1 class="form_heading">
EDIT <%=blog.title%>
</h1>
<form action="/blogs/<%=blog._id%>?_method=PUT" method="POST" class="form">
<div class="form_group">
<label>Title:</label>
<input class="form-control" type="text" name="blog[title]" placeholder="title" value="<%=blog.title%>">
</div>
<div class="form_group">
<label>Image:</label>
<input class="form-control" type="text" name="blog[image]" placeholder="image" value="<%=blog.image%>">
</div>
<div class="form_group">
<label>Content:</label>
<textarea class="form-control" name="blog[body]" placeholder="your post goes here ..." rows="5"><%=blog.body%></textarea>
</div>
<button type="submit" class="btn btn-primary btn-lg">Submit</button>
</form>`enter code here`
</div>
<% include ./partials/footer %>
you have blog in your PUT path but your request is to blogs

Why is my JS logic appearing on index (using ejs/express)

im having an issue understanding why my JS is appearing on my layout. Im currently following along with a tutorial on sitepoint creating forms with in express and when i render the layout.ejs + index.ejs with contact as a partial, the logic on partial is appearing on the page as text.
here is the code:
<div class="form-header">
<% if (Object.keys(errors).length === 0) { %>
<h2>Send us a message aa</h2>
<% } else { %>
<h2 class="errors-heading">Oops, please correct the following:</h2>
<ul class="errors-list">
<% Object.values(errors).forEach(error => { %>
<li><%= error.msg %></li>
<% }) %>
</ul>
<% } %>
</div>
<form method="post" action="/contact" novalidate>
<div class="form-field <%= errors.message ? 'form-field-invalid' : ''
%>">
<label for="message">Message</label>
<textarea class="input" id="message" name="message" rows="4"
autofocus><%= data.message %></textarea>
<% if (errors.message) { %>
<div class="error"><%= errors.message.msg %></div>
<% } %>
</div>
<div class="form-field <%= errors.email ? 'form-field-invalid' : '' %>">
<label for="email">Email</label>
<input class="input" id="email" name="email" type="email" value="<%=
data.email %>" />
<% if (errors.email) { %>
<div class="error"><%= errors.email.msg %></div>
<% } %>
</div>
<div class="form-actions">
<button class="btn" type="submit">Send</button>
</div>
</form>

Cannot read property 'forEach' of undefined node.js

I am getting a .forEach() error on this code
```<% if(locals.isAuthenticated) { %>
<section>
<h4>Leave a comment</h4>
<form method="POST" action="/landmarks/<%= landmark.id %>/comments">
<textarea name="content" id="content" placeholder="Comment"></textarea>
<button class="button">Leave a comment</button>
</form>
</section>
<% } %>
<section>
<h4>Comments</h4>
<% landmark.comments.forEach((comment) => { %>
<p><%= comment.content %></p>
<small><%= comment.createdBy.username %></small>
<small><%= comment.createdAt.toDateString() %></small>
<% if(locals.isAuthenticated && comment.belongsTo(user)) { %>
<form method="POST" action="/landmarks/<%= landmark.id %>/comments/<%= comment.id %>">
<input type="hidden" name="_method" value="DELETE">
<button class="btn">Delete Comment</button>
</form>
<% } %>
<% }) %>
</section>```
I am unsure why this is happening as I i believe this is correct syntax for the forEach method

Resources