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

EJS响应出现Rows is not Iterable Error问题求助

解决EJS中"Rows is not Iterable"错误及SQL查询问题

问题根源分析

  • SQL字段名不匹配:数据库表messages的字段是username,但后端查询条件误用了name,导致查询结果异常甚至返回undefined。
  • 错误分支未处理:SQL执行出错时rows会是undefined,EJS的for...of循环无法迭代undefined,直接触发"not Iterable"错误。
  • 存在SQL注入风险:直接拼接用户输入到SQL语句中,属于不安全的写法。

修正步骤及代码示例

1. 修正SQL查询逻辑并做安全处理

将查询字段名改为username,同时使用参数化查询避免注入,并且在出错时传递空数组:

app.post('/user/post',function(req,res){
  // 用?作为占位符传递参数,修正字段名,同时处理错误分支
  db.all(`SELECT * FROM messages WHERE username = ?`, [req.body.username], (err, rows) => {
    if (err) {
      console.error(err.message);
      // 出错时返回空数组,避免EJS迭代undefined
      return res.render('userinfo', { rows: [] });
    }
    // 确保rows始终是数组,即使查询结果为空
    res.render('userinfo', { rows: rows || [] });
  });
});

2. 给EJS模板添加容错判断

在模板中先判断rows是否有数据,避免空值报错,同时给出友好提示:

<html>
  <head>
    <title>Message Logs</title>
  </head>
  <body>
    <div>
        <% if (rows && rows.length > 0) { %>
            <% for (var row of rows) { %>
                <div><%= row.username %> <%= row.message %></div>    
            <% } %>
        <% } else { %>
            <div>No messages found for this username.</div>
        <% } %>
    </div>
  </body>
</html>

3. 确认数据库表结构一致性

检查SQLite的messages表,确保确实存在username和message字段,无拼写错误。

验证要点

  • 测试存在的用户名,确认能正常显示对应消息。
  • 测试不存在的用户名,确认模板显示"无数据"提示而非报错。
  • 输入含特殊字符的用户名(如' OR 1=1--),验证参数化查询能有效防止SQL注入。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 05:51:30