我一直在玩 express.js 试图返回简单的 json 对象并注意到即使我明确地将 Content-Type
header 设置为 application/json
它仅在状态代码为 200 时的第一个响应中可见。随后的每个 304 响应都没有 Content-Type
header 。
我的代码示例:
app.get('/user', function (req, res) {
res.set('Content-Type', 'application/json');
res.send([
{ user: "john", email: "john@example.com"},
{ user: "marry", email: "marry@example.com"},
{ user: "dan", email: "dan@example.com"}
]);
});
这是什么原因?
最佳答案
304 Not Modified
表示请求包含 conditional header要求服务器响应资源的内容只有当资源已被修改时。
由于没有返回任何内容,因此不会发送 Content-Type
header 。这是 the recommended behavior对于 304 Not Modified
HTTP 回复。
来自 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).
我对 express.js 一无所知,但我会研究正在执行的缓存类型。
关于http - 为什么响应 304 没有 Content-Type header ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31099113/