Node.js+MySQL注册功能报错ER_EMPTY_QUERY: Query was empty求助
解决Node.js + MySQL注册表单的ER_EMPTY_QUERY错误
核心错误原因及修复
1. SQL查询语句语法错误(直接触发ER_EMPTY_QUERY)
在controllers/register.js第9行的db.query调用中,SQL字符串和参数数组之间缺少逗号,JavaScript解析时会把'SELECT email FROM users WHERE email = ?'和[email]当成数组索引操作,最终传递给db.query的第一个参数为空,导致空查询错误。
错误代码:
db.query('SELECT email FROM users WHERE email = ?' [email], async(err, result) => {
修复后:
db.query('SELECT email FROM users WHERE email = ?', [email], async(err, result) => {
2. bcrypt.hash异步操作未正确处理
bcrypt.hash是异步函数,直接赋值会让password变成Promise对象而非哈希后的字符串,需用await等待异步操作完成。
错误代码:
const password = bcrypt.hash(Npassword, 8);
修复后:
const password = await bcrypt.hash(Npassword, 8);
3. 拼写错误(影响前端状态判断)
- 后端返回字段错误:
satus→status - 前端判断逻辑错误:
errpr→error - 成功提示文本错误:
registred→registered
这些拼写问题会导致前端无法正确识别后端返回状态,需统一修正。
完整修复后的controllers/register.js
const db = require("../routes/db-config"); const bcrypt = require("bcryptjs") const register = async (req, res) => { const { email, password: Npassword } = req.body if(!email || !Npassword) return res.json({ status:'error', error:"Please enter your email and password" }); else { console.log(email); db.query('SELECT email FROM users WHERE email = ?', [email], async(err, result) => { if(err) throw err; if(result[0]) return res.json({ status:'error', error:"email already in use" }) else { const password = await bcrypt.hash(Npassword, 8); console.log(password) db.query('INSERT INTO users SET ?', { email: email, password: password }, (error, results)=>{ if (error) throw error; return res.json({ status:"success", success:"account registered successfully" }) }) } }) } } module.exports = register;
额外优化建议
- 给数据库连接添加错误处理,方便排查连接问题:
// routes/db-config.js中添加 db.connect((err) => { if (err) { console.error('数据库连接失败:', err); return; } console.log('数据库连接成功'); });
- 前端表单提交时阻止默认刷新行为:
form.addEventListener("submit", (e) => { e.preventDefault(); // 原有提交逻辑 })
内容的提问来源于stack exchange,提问作者Tijmi
相关产品推荐
相关产品推荐

