You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

渲染EJS页面遇TypeError:无法读取undefined的id属性求助

问题排查:Express+EJS访问/comments/:id路由时TypeError错误

错误原因分析

报错提示Cannot read properties of undefined (reading 'id'),说明传给show.ejs的comment变量是undefined,根源有三点:

1. 新增评论未生成ID

在POST /comments路由中,新增评论时只传入了username和comment,没有给评论添加id属性。当访问对应新评论的/comments/:id(比如/comments/5)时,comments.find()找不到匹配的评论,返回undefined,最终导致渲染EJS时出错。

2. 路由未处理找不到评论的情况

即使访问的ID不存在(比如/comments/100),路由依然会把undefined的comment传给EJS模板,直接触发报错。

3. EJS模板存在语法错误

show.ejs中第11行的<%= comment.comment - comment.username %>使用了减号-,字符串相减会得到NaN,属于明显的语法错误,应该改为字符串拼接形式。


修复方案

1. 给新增评论自动生成ID

修改POST /comments路由,为新评论生成唯一ID:

app.post('/comments',(req,res) =>{
    const {username,comment} = req.body;
    // 生成新ID:取最后一条评论的ID加1,若数组为空则设为1
    const newId = comments.length > 0 ? comments[comments.length - 1].id + 1 : 1;
    comments.push({id: newId, username, comment})
    res.redirect('/comments');
})

2. 路由中处理不存在的评论

在GET /comments/:id路由里,先判断comment是否存在,不存在则返回404:

app.get('/comments/:id',(req,res) =>{
    const{id}= req.params;
    const comment = comments.find(c => c.id === parseInt(id));
    if (!comment) {
        return res.status(404).send('评论不存在');
    }
    res.render('comments/show',{comment})
})

3. 修复EJS模板的语法错误

修改show.ejs的字符串拼接方式:

<body>
    <h1>Your comment #<%= comment.id %> </h1>
    <h2><%= comment.comment %> - <%= comment.username %> </h2>
</body>

4. 可选:EJS模板添加容错判断

为了让模板更健壮,可以在EJS中先判断comment是否存在:

<body>
    <% if (comment) { %>
        <h1>Your comment #<%= comment.id %> </h1>
        <h2><%= comment.comment %> - <%= comment.username %> </h2>
    <% } else { %>
        <h1>评论不存在</h1>
    <% } %>
</body>

内容的提问来源于stack exchange,提问作者OJ23

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 04:54:24