'how to fix "Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client"

*

**> const PORT=8000

const express = require('express')
const {v4:uuidv4}=require('uuid')
const bcrypt =require('bcrypt')
const jwt =require('jsonwebtoken')
const cors=require('cors')
const {MongoClient}=require('mongodb')
const { raw } = require('express')
const uri='mongodb+srv://Adi:[email protected]/Cluster0?retryWrites=true&w=majority'


const app=express()

app.use(cors())
app.use(express.json())

app.get('/',(req,res)=>{
    res.json('hello')
})





app.get('/user', async (req,res)=>{
    const client= new MongoClient(uri)
    const userId=req.query.userId
    console.log('userid',userId)


try{
    await client.connect()
    const database=client.db('app-data')
    const users=database.collection('users')
    const query = {user_id:userId}
    const user= await users.findOne(query)
    console.log('usersss',user)
   res.send(user)

}catch(err){
    console.log(err)

}

finally{
    await client.close()
}
})


app.post('/signup',async (req,res)=>{

    const client= new MongoClient(uri)
    const {email,password}=req.body

    const generateeduderId=uuidv4();
    const hashedpassword= await bcrypt.hash(password,10)

    try{
        await client.connect()
        const database=client.db('app-data')
        const users= database.collection('users')

      const existingUser= await users.findOne({email})

      if(existingUser){
          return res.status(409).send('User already exists...😏 Please Login')
                    }


      const sanitizedEmail=email.toLowerCase()
      const data={
          user_id:generateeduderId,
          email:sanitizedEmail,
          hashed_password:hashedpassword
                }


      const inserteduser = await users.insertOne(data)
      const token=jwt.sign(inserteduser,sanitizedEmail,{
          expiresIn:60*24,
      })

        res.status(201).json({token,userId:generateeduderId })
    }
    
    catch(err){
        console.log(err)

    }


})






app.post('/login',async(req,res)=>{
    const client= new MongoClient(uri)
    const {email,password}=req.body
    
    try{
        await client.connect()
        const database=client.db('app-data')
       const users= database.collection('users')
         const user=await users.findOne({email})


         const correctpassword= await bcrypt.compare(password,user.hashed_password)

         if(user && correctpassword){ 
            const token=jwt.sign(user,email,{
                expiresIn:60*24
            })
            res.status(201).json({token,userId:user.user_id})
         }
          
         res.status(400).send('Invalid Credentials')
    }
    catch(err){
        console.log(err)
    }


})





app.get('/users', async(req,res)=>{
   const client= new MongoClient(uri)

   try{
       await client.connect()
        const database=client.db('app-data')
       const users= database.collection('users')

      const returnedUsers=await users.find().toArray()
      res.send(returnedUsers)


   }
   finally{
       await client.close()
   }
})










app.put('/user', async(req,res)=>{
    const client= new MongoClient(uri)
    const formData=req.body.formData

    console.log(formData)

  try{
 
    await client.connect()
    const database=client.db('app-data')
    
    const users=database.collection('users')
    const query= {user_id:formData.user_id}


    const updateDocument={
        $set:{
            first_name:formData.first_name,
            dob_day:formData.dob_day,
            dob_month:formData.dob_month,
            dob_year:formData.dob_year,
            show_gender:formData.show_gender,
            gender_identity:formData.gender_identity,
            gender_interest:formData.gender_interest,
            url:formData.url,
            about:formData.about,
            matches:formData.matches

        },
    }

   const inserteduser= await users.updateOne(query,updateDocument)
   res.send(inserteduser)
  }
  finally{
      await client.close()
  }

})



app.listen(PORT,()=>{
    console.log(`server running on port ${PORT}`)
})




***

    error
    server running on port 8000
    Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
    at new NodeError (node:internal/errors:371:5)
    at ServerResponse.setHeader (node:_http_outgoing:576:11)
        at ServerResponse.header (C:\Users\aadar\Desktop\chat\seayo\server\node_modules\express\lib\response.js:776:10)
       at ServerResponse.send
(C:\Users\aadar\Desktop\chat\seayo\server\node_modules\express\lib\response.js:170:12)
       at C:\Users\aadar\Desktop\chat\seayo\server\index.js:120:26 {
     code: 'ERR_HTTP_HEADERS_SENT'
    }



Solution 1:[1]

You are returning the response twice. "res.status" is being called twice in "/users" get api.

As the response is already sent with the headers, it throws an error that you are not allowed to set headers twice.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Akshay Raut