8

I have the case that a express controller action "may" send contents.

"Send" means either content was send (http 200) or the http status was set to something (http status 204 or a redirect for example)

If nothing was sent/set a default routine should send a default content.

how can i test in my default routine if the express controller action already set contents or set the status code ?

lgersman
  • 2,178
  • 2
  • 19
  • 21
  • How are you hooking up your 'default routine'? A more common approach would be for your controller action to call `next()` if it doesn't have to send anything. – robertklep Mar 08 '13 at 07:31
  • its a bit more complicated ... the simple question is : how can i track if http status/content was already written to response ? – lgersman Mar 08 '13 at 08:05
  • There is no API for that, only hacks (like setting a custom property on `res` in your controller or checking for `res.finished` with all forms of asynchronous issues and possibilities of breaking with Express updates). – robertklep Mar 08 '13 at 08:12
  • 1
    see that : http://stackoverflow.com/questions/12030107/express-js-how-to-check-if-headers-have-already-sent – Cédric NICOLAS Jun 17 '15 at 22:42

1 Answers1

10

response.headersSent should work.

For example:

if (response.headersSent) {
    console.log('Headers sent!')
} else {
    console.log('Headers have not been sent.')
}
res.writeHead(200);
if (response.headersSent) {
    console.log('Headers sent!')
} else {
    console.log('Headers have not been sent.')
}

Connecting with a client should log:

Headers have not been sent.
Headers sent!
Bennett
  • 1,007
  • 4
  • 15
  • 29
  • In my testing, it seemed that this property isn't set immediately following a call to `res.send()`, so you may want to use `setTimeout` to ensure that it has a chance to be updated first :) – MalcolmOcean Apr 17 '18 at 18:10
  • @MalcolmOcean the reason for that is that res.send asynchronously sends the headers, so it might take some time for the property to be set. Do not use `setTimeout`. Please. There should be a callback on res.send (maybe undocumented) – Bennett Apr 17 '18 at 18:51
  • The context where I used this was inside an error handler, where I had to figure out if the error occurred before the headers were sent (in which case just send me an email) or after the headers were sent (in which case the user needs a 500 &/ error page or the page will time out). If you have a better suggestion for this context, I'm all ears! – MalcolmOcean Apr 18 '18 at 00:30