I am using Express with Body Parser. Given a below header key:
X-Master-Key
When I am using the below code snippet, it fails to output the value
req.headers['X-Master-Key'] // Fails
but when the above is changed to, it works
req.headers['x-master-key'] // Works
Further, when I tried to output req.headers
, it turns out that Express outputs all the headers in a down-case format.
I started digging down further and tried using the below code, either of these snippets work
req.header('X-Master-Key'); // Works
// -- OR
req.header('x-master-key'); // Works
So what's the issue here? Why does Express changes all header keys to down-case? Moreover, how using req.header()
is different from req.headers[]
?
The problem arises because in the HTTP protocol, headers are case-insensitive. This means that content-type
, Content-Type
, and coNTEnt-tYPe
all refer to the same header, and the Express framework needs to be able to handle any of them.
The different between req.headers
(the object) and req.header
(the function) is simply this:
If you want to get a property from a Javascript object, the property name is case-sensitive. So req.headers['content-type']
will work; req.headers['Content-Type']
will not. Why does the lower case version work? Because the Express framework, in an attempt to handle all the different possible cases (remember, HTTP will allow anything), converts everything to lower case.
But the developers of Express recognize that you (the developer) might be looking for Content-Type
and you might not remember to convert to lower case, so they provided a function, req.header
, which will take care of that for you.
So, in short:
This is recommended:
const myHeader = req.header('Content-Type');
Use whatever case you want - the function will convert it to lower case and look up the value in req.headers
.
This is not recommended:
const myHeader = req.headers['Content-Type'];
If you don't use a lower-case header name, you won't get what you expect.