I've been playing with express.js trying to return simple json object and noticed that even though I explicitly set Content-Type
header to be application/json
it is only visible on first response when status code is 200. Every following response with 304 won't have Content-Type
header.
My code sample:
app.get('/user', function (req, res) {
res.set('Content-Type', 'application/json');
res.send([
{ user: "john", email: "[email protected]"},
{ user: "marry", email: "[email protected]"},
{ user: "dan", email: "[email protected]"}
]);
});
What is the reason for that?
"[...] a missing Content-Type header which means that this website could be at risk of a MIME-sniffing attacks. [...] The problem arises once a website allows users to upload content which is then published on the web server.
The 304 response MUST NOT contain a message-body, and thus is always terminated by the first empty line after the header fields.
The Content-Type header is used in web requests to indicate what type of media or resource is being used in the request or response. When you send data in a request such as PUT or POST, you pass the Content-Type header to tell the server what type of data it is receiving.
304 Not Modified
means that the request contained a conditional header asking the server to respond with the contents of the resource only if the the resource has been modified.
Since no content is being returned, the Content-Type
header is not sent. This is the recommended behavior for a 304 Not Modified
HTTP reply.
From RFC 7232 §4.1 :
The server generating a
304
response MUST generate any of the
following header fields that would have been sent in a200 (OK)
response to the same request:Cache-Control
,Content-Location
,Date
,ETag
,Expires
, andVary
.Since the goal of a
304
response is to minimize information transfer when the recipient already has one or more cached representations, a sender SHOULD NOT generate representation metadata other than the above listed fields unless said metadata exists for the purpose of
guiding cache updates (e.g.,Last-Modified
might be useful if the
response does not have anETag
field).
I don't know anything about express.js, but it I would look into what sort of caching is being done.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With