I recently read koa.js source code, and found there are some conditional judgement on headersSent which is node.js api.So I want to know why we need to do this judgement?
2 Answers
If headersSent
is true then that literally means that headers have been already sent and from that point you cannot add/set any additional headers (train has gone that is, you are late and cannot ride it anymore).
So if we have to mess with headers it is important to know when it is possible and when it's not. Hence the headersSent
conditional.
If you post the exact code piece of interest, we will be able to tell you more.

- 16,124
- 24
- 94
- 138
-
I just found an exhaustive answer on SO, listing the methods that can/should be called before/after headers are sent: https://stackoverflow.com/a/7086621/189673 – jayarjo Feb 16 '19 at 08:24
According to the HTTP protocol specification, the HTTP answer consists of 2 parts (usually)
header: which sets the response code, manages the cache and sets cookies (and couple other things)
body: the content of the answer.
Body can be send in parts (Immortal flush()
from PHP), the header is always at the beginning and if you send the end marker, you can not add another field.
And that's what 'headersSent` means - if you can change the headline.

- 2,695
- 1
- 18
- 26