http - "Cache request directives"和 "Cache response directives"都需要吗?

标签 http caching web http-headers

如果我已经有了“缓存请求指令”,那么“缓存响应指令”有什么意义呢?他们添加了什么吗?如果没有它们,我的应用程序是否可以正常运行?

我正在寻找“缓存响应指令”是否多余的证据。如果它们是多余的,我不会理会它们。

GC_

最佳答案

我假设您是作为应用程序开发人员询问的,如果是这样,您不应该为您的应用程序在请求中收到的任何 Cache-Control header 而烦恼。

为什么? 因为该 Cache-Control header 用于在请求到达您的应用程序之前进行缓存。 它不适用于您的应用程序。

这在 RFC7234 Section 5.2 中有解释(强调我的):

The "Cache-Control" header field is used to specify directives for caches along the request/response chain.

header 的目的是告诉缓存如何处理请求。 您的应用程序收到 header ,因为它附加到请求。 但仅仅因为您收到它,并不意味着它适合您。

底线:忽略请求中的任何 Cache-Control header 。

响应中的缓存控制来自您的应用程序,它也用于缓存。 你用它来告诉缓存如何处理响应。 基本上,您使用 header 来指定响应是否可缓存,如果是,缓存多长时间。 它不仅仅是请求中收到的 Cache-Control header 的副本。

Do they add anything?

是的,他们有。 响应中的 Cache-Control 告诉缓存响应是否可缓存,如果是, 它允许缓存使用缓存的响应立即为等效请求提供服务。 从客户端的角度来看,这可以减少应用程序的负载并缩短响应时间。

RFC7234 Section 4.2状态:

When a response is "fresh" in the cache, it can be used to satisfy subsequent requests without contacting the origin server, thereby improving efficiency.

你的下一个问题:

Will my application run the same without them?

这取决于。 如果您的应用程序没有为不得缓存的响应添加适当的 Cache-Control header ,则 future 的请求可能会收到过时的响应。 因此,我建议至少将 Cache-Control: no-cache 添加到不得缓存的响应中。

在评论部分对您的问题进行补充说明

header 通常应该来自您的后端,而不是您的前端。 这允许缓存准确地加速对后端的请求并保持前端请求代码简单。 有一个异常(exception):如果后端不是您的并且其响应新鲜度政策不符合您的要求。

示例场景可能是有序的:

Let's say, that in addition to sending requests to your own backend, your frontend also sends requests to someone else's backend. This particular backend specifies that its responses are cacheable for at most 5 minutes, by either sending Cache-Control: max-age=300 or appropriate Expires header.

Let's also say, that you want the responses to be no more than 10 seconds stale, because 5 minutes is too stale for you.

Since the backend isn't yours, you can't change the 5-minutes directive, but you can send your requests with Cache-Control: max-age=10 thereby forcing the caches to fetch a fresh response if a cached response is older than 10 seconds, despite the 5-minutes directive from the backend.

这是从您的前端发送 Cache-Control header 的适当情况:后端不是您的并且其响应新鲜度策略不符合您的要求。

关于http - "Cache request directives"和 "Cache response directives"都需要吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46003453/

相关文章:

php - 我应该如何通过 AJAX 发出长 PHP 请求,定期检查状态更新,并在请求取消时关闭脚本?

c++ - 从 C++ 返回 JSON 对象到 HTTP POST REST 调用

javascript - Node.js process.nextTick 仍然阻止服务器获取请求

css - 清除 Windows Server 2012 上的缓存

javascript - 不要让在输入中写入大于 max 属性的数字

c++ 复制文件\通用实现

internet-explorer - 有没有办法让 Internet Explorer 不缓存特定网站?

C# "cached debug log"

python - 单元测试 Web 应用程序

ssl - 内网应用程序中具有自签名证书的 Websocket 服务器