在使用 Cloudflare 页面规则缓存之前验证响应

validate response before caching with Cloudflare page rule

我创建了一个 Cloudflare 页面规则来缓存静态页面,如下所示:

domain.com/
Cache Level: cache everything
Edge Cache TTL: 2 hours

一般没有问题,但是有几次服务器返回错误,或者连接超时,Cloudflare缓存了这个结果。如何在缓存页面之前测试有效响应?

您应该能够在进行任何缓存之前检查响应的状态。

response.ok returns true if the status code is within 200 to 299. You can interrogate the status directly with response.status

const response = await fetch(event.request);
if(response.ok) {
    // ... do caching logic
}