登录接口MySQL查询异常:数据存在但无返回结果
排查Node.js MySQL登录查询返回rows undefined的问题
1. Promise回调参数顺序错误
mysql模块的query方法使用Promise风格调用时,resolve的结果直接是查询到的rows,错误会被reject到catch逻辑中,而非作为then的第一个参数。你当前的代码把err放在then的第一个参数位置,导致实际的查询结果被赋值给了err变量,rows变量因此拿到undefined,后续判断rows.length自然出错。
修复后的查询代码:
dbConnection.query(`SELECT password FROM accounts WHERE username = '${username}'`) .then((rows) => { // 仅接收rows参数 console.log("查询结果:", rows); if (rows.length !== 0) { var password_hash = rows[0]['password']; const verified = bcrypt.compareSync(password, password_hash); if (verified) { res.send(rows[0]); } else { res.send({err: "Invalid password"}); } } else { res.send({err: "Invalid username or password"}); } }) .catch((err) => { // 在catch中捕获数据库查询错误 console.error("数据库查询错误:", err); res.send({err: "Database query failed"}); });
2. 存在SQL注入风险
你通过字符串拼接构造SQL语句,不仅会导致用户名含特殊字符(如单引号)时出现语法错误,还会引发严重的SQL注入攻击。必须改用参数化查询:
// 用?作为占位符,第二个参数传入参数数组 dbConnection.query('SELECT password FROM accounts WHERE username = ?', [username]) .then((rows) => { // 后续逻辑同上 }) .catch((err) => { console.error("查询错误:", err); res.send({err: "Database error"}); });
3. 数据库连接的优化点
你创建连接后未显式调用connect(),虽然mysql的query会自动尝试连接,但显式处理连接错误更稳妥;同时建议使用连接池(createPool)替代单次连接,避免频繁创建销毁连接的性能损耗:
// 创建连接池示例 const pool = mysql.createPool({ host: "localhost", database: "testapp", user: "root", password: "", socketPath: "" }); // 使用连接池执行查询 pool.query('SELECT password FROM accounts WHERE username = ?', [username]) .then(rows => { /* ... */ }) .catch(err => { /* ... */ });
4. 冗余的res.end()调用
res.send()方法会自动完成响应并结束连接,无需额外调用res.end(),重复调用可能引发异常。
内容的提问来源于stack exchange,提问作者Jaydendev
相关产品推荐
相关产品推荐

