Nodejs连接数据库报“Cannot set headers after they are sent to the client“

我这里是使用mysql + nodejs,请求接口后就直接爆出这个问题,然后就仔细检查了一下代码,发现以下问题,就对应的解决方案,目前已经解决。
在这里插入图片描述
在上面循环中会有两次使用send方法,就会报这个问题,直接return掉就行了。

app.post('/test_post',(request,response)=>{
    
    
  let {
    
     username, password } = request.body
  
  connection.query('select * from user',(error,result,fields)=>{
    
    
    if(!error){
    
    
      for(let i = 0; i < result.length; i++){
    
    
        if(result[i].username == username && result[i].password == password){
    
    
          return response.send({
    
    
            code:200,
            data:'登录成功'
          })
        }else{
    
    
          return response.send({
    
    
            code:500,
            data:'服务器错误'
          })
        }
      }
      // 关闭链接
      connection.end()
    }
  })
})

猜你喜欢

转载自blog.csdn.net/cautionHua/article/details/114672919