本页还没有译文
本页 67 段还没译成繁體中文,下面显示的是英文原文。Cache
还没翻译译自英文(developers.cloudflare.com)本页 67 段都还没译
Background
The Cache API allows fine grained control of reading and writing from the Cloudflare global network cache.
Note
The Cache API is a programmatic interface for reading from and writing to Cloudflare's cache from inside a Worker. To cache responses from your Worker so that Cloudflare returns them without executing your Worker, use Workers Caching instead. The two mechanisms are independent.
The Cache API is available globally but the contents of the cache do not replicate outside of the originating data center. A GET /users response can be cached in the originating data center, but will not exist in another data center unless it has been explicitly created.
Workers deployed to custom domains have access to functional cache operations. So do Pages functions, whether attached to custom domains or *.pages.dev domains.
However, any Cache API operations in the Cloudflare Workers dashboard editor and Playground previews will have no impact. For Workers fronted by Cloudflare Access, the Cache API is not currently available.
Note
This individualized zone cache object differs from Cloudflare’s Global CDN. For details, refer to How the cache works.
Accessing Cache
The caches.default API is strongly influenced by the web browsers’ Cache API, but there are some important differences. For instance, Cloudflare Workers runtime exposes a single global cache object.
let cache = caches.default;
await cache.match(request);You may create and manage additional Cache instances via the caches.open method.
let myCache = await caches.open('custom:cache');
await myCache.match(request);Headers
Our implementation of the Cache API respects the following HTTP headers on the response passed to put():
Cache-Control- Controls caching directives. This is consistent with Cloudflare Cache-Control Directives. Refer to Edge TTL for a list of HTTP response codes and their TTL when
Cache-Controldirectives are not present.
- Controls caching directives. This is consistent with Cloudflare Cache-Control Directives. Refer to Edge TTL for a list of HTTP response codes and their TTL when
Cache-Tag- Allows resource purging by tag(s) later.
ETag- Allows
cache.match()to evaluate conditional requests withIf-None-Match.
- Allows
Expiresstring- A string that specifies when the resource becomes invalid.
Last-Modified- Allows
cache.match()to evaluate conditional requests withIf-Modified-Since.
- Allows
This differs from the web browser Cache API as they do not honor any headers on the request or response.
Note
Responses with Set-Cookie headers are never cached, because this sometimes indicates that the response contains unique data. To store a response with a Set-Cookie header, either delete that header or set Cache-Control: private=Set-Cookie on the response before calling cache.put().
Use the Cache-Control method to store the response without the Set-Cookie header.
Methods
Put
cache.put(request, response);-
put(request, response): Promise- Attempts to add a response to the cache, using the given request as the key. Returns a promise that resolves to
undefinedregardless of whether the cache successfully stored the response.
- Attempts to add a response to the cache, using the given request as the key. Returns a promise that resolves to
Note
The stale-while-revalidate and stale-if-error directives are not supported when using the cache.put or cache.match methods.
Parameters
-
requeststring | Request- Either a string or a
Requestobject to serve as the key. If a string is passed, it is interpreted as the URL for a new Request object.
- Either a string or a
-
responseResponse- A
Responseobject to store under the given key.
- A
Invalid parameters
cache.put will throw an error if:
- The
requestpassed is a method other thanGET. - The
responsepassed has astatusof206 Partial Content. - The
responsepassed contains the headerVary: *. The value of theVaryheader is an asterisk (*). Refer to the Cache API specification for more information.
Errors
cache.put returns a 413 error if Cache-Control instructs not to cache or if the response is too large.
Note
cache.put will silently reject a 301 or 302 redirect response if both of the following are true:
- The cache key does not include the query string (for example, a custom cache key set via Workers or Page Rules that strips the query string).
- The
Locationheader in the redirect response contains the request's query string.
This is a cache-poisoning mitigation. To cache redirect responses with query strings, either include the query string in your cache key, or remove the query string from the Location header before calling cache.put(). This restriction does not apply on .workers.dev domains, which include the query string in the cache key by default.
Match
cache.match(request, options);-
match(request, options): Promise<Response | undefined>- Returns a promise wrapping the response object keyed to that request.
Note
The stale-while-revalidate and stale-if-error directives are not supported when using the cache.put or cache.match methods.
Parameters
-
requeststring | Request- The string or
Requestobject used as the lookup key. Strings are interpreted as the URL for a newRequestobject.
- The string or
-
options- Can contain one possible property:
ignoreMethod(Boolean). Whentrue, the request is considered to be aGETrequest regardless of its actual value.
- Can contain one possible property:
Unlike the browser Cache API, Cloudflare Workers do not support the ignoreSearch or ignoreVary options on match(). You can accomplish this behavior by removing query strings or HTTP headers at put() time.
Our implementation of the Cache API respects the following HTTP headers on the request passed to match():
-
Range- Results in a
206response if a matching response with a Content-Length header is found. Your Cloudflare cache always respects range requests, even if anAccept-Rangesheader is on the response.
- Results in a
-
If-Modified-Since- Results in a
304response if a matching response is found with aLast-Modifiedheader with a value before the time specified inIf-Modified-Since.
- Results in a
-
If-None-Match- Results in a
304response if a matching response is found with anETagheader with a value that matches a value inIf-None-Match.
- Results in a
Note
cache.match() never sends a subrequest to the origin. If no matching response is found in cache, the promise that cache.match() returns is fulfilled with undefined.
Errors
cache.match generates a 504 error response when the requested content is missing or expired. The Cache API does not expose this 504 directly to the Worker script, instead returning undefined. Nevertheless, the underlying 504 is still visible in Cloudflare Logs.
If you use Cloudflare Logs, you may see these 504 responses with the RequestSource of edgeWorkerCacheAPI. Again, these are expected if the cached asset was missing or expired. Note that edgeWorkerCacheAPI requests are already filtered out in other views, such as Cache Analytics. To filter out these requests or to filter requests by end users of your website only, refer to Filter end users.
Delete
cache.delete(request, options);delete(request, options): Promise<boolean>
Deletes the Response object from the cache and returns a Promise for a Boolean response:
true: The response was cached but is now deletedfalse: The response was not in the cache at the time of deletion.
Global purges
The cache.delete method only purges content of the cache in the data center that the Worker was invoked. For global purges, refer to Purging assets stored with the Cache API.
Parameters
-
requeststring | Request- The string or
Requestobject used as the lookup key. Strings are interpreted as the URL for a newRequestobject.
- The string or
-
optionsobject- Can contain one possible property:
ignoreMethod(Boolean). Consider the request method a GET regardless of its actual value.
- Can contain one possible property: