So I'm following this youtube tutorial, and it's gotten to a part where I should display an error message using an ejs partial. followed the tutorial to a T, but i get this error:
ReferenceError: C:\PATH\mongo_db_app\views\layouts\layout.ejs:11
9| <body>
10| <%- include('../partials/header.ejs') %>
>> 11| <%- include('../partials/err_msg.ejs') %>
12| <%- body %>
13| </body>
14| </html>
C:\PATH\mongo_db_app\views\partials\err_msg.ejs:1
>> 1| <%= errorMessage %>
errorMessage is not defined
at eval (eval at compile (C:\PATH\mongo_db_app\node_modules\ejs\lib\ejs.js:673:12), <anonymous>:10:26)
at err_msg (C:\PATH\mongo_db_app\node_modules\ejs\lib\ejs.js:703:17)
at include (C:\PATH\mongo_db_app\node_modules\ejs\lib\ejs.js:701:39)
at eval (eval at compile (C:\PATH\mongo_db_app\node_modules\ejs\lib\ejs.js:673:12), <anonymous>:15:17)
at layout (C:\PATH\mongo_db_app\node_modules\ejs\lib\ejs.js:703:17)
at tryHandleCache (C:\PATH\mongo_db_app\node_modules\ejs\lib\ejs.js:274:36)
at exports.renderFile [as engine] (C:\PATH\mongo_db_app\node_modules\ejs\lib\ejs.js:491:10)
at View.render (C:\PATH\mongo_db_app\node_modules\express\lib\view.js:135:8)
at tryRender (C:\PATH\mongo_db_app\node_modules\express\lib\application.js:657:10)
at Function.render (C:\PATH\mongo_db_app\node_modules\express\lib\application.js:609:3)
The err_msg.ejs contains one line, namely <%= errorMessage %>
. The layout file in which it is used is:
<!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>Mybrary</title>
</head>
<body>
<%- include('../partials/header.ejs') %>
<%- include('../partials/err_msg.ejs') %>
<%- body %>
</body>
</html>
And this is the code block where errorMessage
is coming from:
router.post('/', (req,res) => {
const author = new Author({
name: req.body.name
})
author.save((err, newAuthor) => {
if (err){
res.render('authors/new', {
author: author,
errorMessage: 'Error creating author'
})
} else {
//res.redirect(`authors/${newAuthor.id}`)
res.redirect(`authors`)
}
})
})
For more info, here is the github repo: https://github.com/DragosSaviour/Mybrary
Can someone help me understand/solve this problem?
EDIT: I have tried doing
<%if (errorMessage) { %>
<%= errorMessage %>
<% } %>
the result remains the same.
CodePudding user response:
You need to check if errorMessage
exits, if it's not undefined with typeof
(your attempt checks if it's truthy, which is why it fails, because it doesn't exist).
Try this:
<%if (typeof errorMessage != "undefined") { %>
<%= errorMessage %>
<% } %>