Arvind kumar
Arvind kumar

Reputation: 87

UnhandledPromiseRejectionWarning: Cannot set headers after they are sent to the client(closed)

I created one program that first i used res.status(200).send("some html code") then redirect

Here is example

app.get('/callback',async(req,res)=>{
 res.status(200).send("html code")
 res.redirect('/path/url')

})

Error

Cannot set headers after they are sent to the client

Upvotes: 0

Views: 47

Answers (2)

Arvind kumar
Arvind kumar

Reputation: 87

app.get('/callback',async(req,res)=>{
 res.status(200).send("html code") //Remove this 
 res.redirect('/path/url')

})

app.get('/path/url',async(req,res)=>{
 res.status(200).send("html code") //put here 
})

Upvotes: 0

Joachim Sauer
Joachim Sauer

Reputation: 308031

tl;dr Remove line res.status(200).send("html code") entirely.

There's much confusion going on:

  • Status code 200 implies there's no redirect, as a redirect would be 301 or 302.
  • Calling send signals to the framework "I'm done here, send this stuff". You can't modify anything about the response after that. Sending a redirect would require you to send a different response.
  • Sending content of any kind (such as the HTML you mention) on a redirect is not forbidden, but it is unusual, since most clients will just follow the redirect to get the actual content and pretty much ignore the content in the response.

In short:

  • res.status(200) is pointless if you want to redirect, as that will change the status code anyway.
  • res.send("html code") is not in itself a problem, but unusual and can probably be left out entirely.

Upvotes: 1

Related Questions