11. “Cannot set headers after they are sent to the client”解决方案----关于query数据库异步查询
问题:“Cannot set headers after they are sent to the client”报错
开始查询答案的时候,网上给的答案全都是清一色的”多个res.send导致出错”,很容易找到解决方案即“关于加return解决”。
贴上自己的错误代码:
const express = require("express")
const db=require("../db/index")
//引入对密码进行加密
const bcrypt=require('bcryptjs')
exports.regUser = (req,res)=>{
const userinfo=req.body
const sql=`select * from ev_users where username=?`
db.query(sql,[userinfo.username],(err,results)=>{
/*我的查询代码*/
}
const sql_insert=`insert into ev_users set ? `
db.query(sql_insert,info,(err,results)=>{
/*我的第二段查询代码*/
}
}
代码结构大概是这个样子,当然也都对res.send都做了return处理,但是仍然报错,这个错误花费了我一下午的时间,相信也有小伙伴会在这里卡着。
然后。。。。在一篇博客里面看到了异步这个词,突然想起来是否是因为自己的查询是在函数中是并列的。回头一看,还真是,并列查询会导致多个进程的创建,因此可能有多个send。。。。。