问题描述
更改用户密码时,快速提交密码后报错
捕获错误:Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
node报错信息:[nodemon] app crashed - waiting for file changes before starting…
exports.updatePwd = (req, res) => {
// 查询用户id、username、password
console.log(req.body, '输入的信息');
const sql = 'select * from ev_users where id=?'
// 从Token中拿id:req.auth.id
db.query(sql, req.auth.id, (err, results) => {
// 数据库错误
if (err) return res.cc(err)
// 查询成功会返回一条数据
if (results.length !== 1) return res.cc('用户不存在')
// 解密数据库中的密码和输入的密码对比
const compare = bcrypt.compareSync(req.body.oldPwd, results[0].password)
// 旧密码与数据库不一样,输出错误
if (!compare) {
return res.cc('旧密码错误')
}
// 旧密码正确,开始处理新密码
// 加密新密码
const hashPwd = bcrypt.hashSync(req.body.password, 5)
// 更新sql的语句
const sql = 'update ev_users set password=? where id=?'
// 处理更新结果
db.query(sql, [hashPwd, req.auth.id], (err, results) => {
if (err) {
return res.cc('数据库错误异常')
}
if (results.affectedRows !== 1) {
return res.cc('更用户信息新失败')
}
return res.cc('更新用户成功', 0)
})
})
}
原因分析:
上面代码中,对于每个传入请求,只能发送一个响应。此特定错误消息告诉您代码正在尝试发送两个请求。大多数情况下,发生这种情况是因为使用异步函数对代码进行不正确的排序,当快速多次提交时,该异步函数没有来得及执行完毕,导致异步队列错乱
const compare = bcrypt.compareSync(req.body.oldPwd, results[0].password)
解决方案:
使用 async/await 将数据库查询处理函数为异步函数
db.query(sql, req.auth.id, async (err, results) => { //处理函数}
将里面异步代码设为 等待异步处理函数,执行完再继续向下执行
const compare = await bcrypt.compareSync(req.body.oldPwd, results[0].password)