You need to enable JavaScript to run this app. 如何解决Node.js中TypeError: Cannot read property 'length' of undefined报错
优惠活动
大模型
产品
解决方案
定价
更多

如何解决Node.js中TypeError: Cannot read property 'length' of undefined报错

错误原因
  • 核心触发点:你在数据库查询回调中直接读取results.length,但查询执行失败时results会是undefined,读取不存在的属性就抛出了该类型错误。
  • 直接诱因:SQL语句存在拼写错误,你写的SELECT * FORM accounts中FORM是错误拼写,正确的查询关键字是FROM,语法错误导致数据库查询直接失败,没有返回结果集。
  • 潜在诱因:代码未做数据库错误捕获,即使没有拼写错误,遇到数据库连接中断、表不存在、权限不足等问题时,也会出现同样报错。
解决方案

按以下步骤修改代码即可解决:

  1. 修正SQL语句的拼写错误
  2. 在查询回调中优先判断是否有错误,提前处理异常场景
  3. 增加results存在性判断,提升代码健壮性

修正后的/auth接口参考代码:

app.post('/auth', function(request, response) {
    var username = request.body.username;
    var password = request.body.password;
    if (username && password) {
        // 修正FORM为FROM
        connection.query('SELECT * FROM accounts where username = ? AND password = ?', [username, password], function(error, results, fields) {
            // 新增错误处理逻辑
            if (error) {
                response.send('数据库查询异常,请稍后重试');
                return response.end();
            }
            // 新增results存在判断再读取length
            if (results && results.length > 0) {
                request.session.loggedin = true;
                request.session.username = username;
                response.redirect('/home')
            } else {
                response.send('Incorrect Username or Password');
            }
            response.end();
        })
    } else {
        response.send('Please enter Username and Password!');
        response.end();
    }
})

额外优化建议:当前代码是明文存储和比对密码,存在安全风险,后续迭代建议对密码做加盐哈希存储。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.16 13:06:06