首页 > 解决方案 > Cloudflare 工作人员:防止带有参数的 URL 的 302(来自磁盘缓存)

问题描述

我有一个工作人员,我想在 URL 以这种方式具有特定参数时绕过缓存:

      let wcApiParam = url.searchParams.get('wc-api');

      //bypass cache if wc-api param is in the URL
      if( wcApiParam != 'auth'  ){
        //force cache
        response = await fetch( newRequest, { cf: { cacheTtl: 43200 } } );
      } else {
          //bypass cache
          response = await fetch( newRequest, { cf: { cacheTtl: 0 } } );
      }

我不确定我做错了什么,请求的响应总是302 (from disk cache)这会导致我的站点出现错误,因为我需要避免这些请求被缓存。我的工人可能有什么问题?或者我的缓存设置有问题?

以下是完整回复:

请求响应

标签: javascriptservice-workerbrowser-cachecloudflarecloudflare-workers

解决方案


看起来问题在于响应已缓存在浏览器的缓存中。该请求实际上根本没有命中 Cloudflare(因此您的 Worker 没有执行)。

浏览器缓存了响应,因为它有Cache-Control: max-age=14400. 这告诉浏览器它可以将响应缓存 4 小时。您应该停止从您的源发送此标头,或者您可以让您的 Worker 脚本从不应缓存在浏览器中的响应中删除标头,例如:

let response = await fetch(...);

// Copy the response so that headers can be modified.
response = new Response(response);

// Remove cache-control header.
response.headers.delete("Cache-Control");

推荐阅读