http - 为什么响应 304 没有 Content-Type header ?

标签 http express http-headers

我一直在玩 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 a 200 (OK)
response to the same request: Cache-Control, Content-Location, Date,
ETag, Expires, and Vary.

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 an ETag field).

我对 express.js 一无所知,但我会研究正在执行的缓存类型。

关于http - 为什么响应 304 没有 Content-Type header ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31099113/

相关文章:

python - 使用 Python 计算内容长度

node.js - 如何从 Node js中的http post请求获取上传进度信息?

http - flutter http header

ruby - 使用 Rails 转发未经处理的多部分 HTTP 请求

javascript - 无法从从 sql 数据库读取的 JavaScript 函数获取返回数组

python - 如何确定在 Python 中使用 HTTP 下载的内容的文件名?

javascript - 访问 $http 中的 'Set-Cookies' header

ajax - 是访问控制允许来源 : * unsafe?

javascript - 如何检查 Node JS 服务器端代码中是否启用了 javascript

node.js - Express.js : how to make express. static 的优先级高于应用程序的其余部分?