1

I'm trying to make conditional res.send with if/else statement.

It works. However, after few second my server crash and i got this error

Error: Can't set headers after they are sent.

I update my response so that it's looks like return res.send... But i'm still facing the same issue.

I really need to set my response conditionally and for my app logic i can't set the response outside the if/else. Especially for synchronous purposes.

So how to prevent my server to crash ?

Exemple with firebase :

if(req.body.hasOwnProperty('simplePost')){
      var postRef = admin.database().ref('post')
      postRef.once('value').then((snap)=>{
        if(!snap.exists()){
          return false
        }else{
          postRef.set(data)
          return res.status(200).end()
        }
      })
    }else if(req.body.hasOwnProperty('postWithRedirect')){
      var postRef = admin.database().ref('post')
      postRef.once('value').then((snap)=>{
        if(!snap.exists()){
          return false
        }else{
          postRef.set(data)
          return res.status(200)send({redirectUrl:snap.child('url').val()}).end()
        }
      })
    }
John doe
  • 3,680
  • 7
  • 31
  • 65

0 Answers0