所以我正在關注這個 youtube 教程,它已經到了我應該使用 ejs 部分顯示錯誤訊息的部分。按照教程進行了 T,但我收到此錯誤:
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)
err_msg.ejs 包含一行,即<%= errorMessage %>. 使用它的布局檔案是:
<!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>
這是errorMessage來自的代碼塊:
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`)
}
})
})
有關更多資訊,這是 github 存盤庫:https ://github.com/DragosSaviour/Mybrary
有人可以幫我理解/解決這個問題嗎?
編輯:我試過做
<%if (errorMessage) { %>
<%= errorMessage %>
<% } %>
結果保持不變。
uj5u.com熱心網友回復:
您需要檢查是否errorMessage退出,如果它不是 undefined with typeof(您的嘗試檢查它是否為truthy,這就是它失敗的原因,因為它不存在)。
嘗試這個:
<%if (typeof errorMessage != "undefined") { %>
<%= errorMessage %>
<% } %>
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/534595.html
標籤:节点.js表示ejs
上一篇:如何為此撰寫測驗用例?
下一篇:無法發布;不能用反應軸制作帖子
