首页 > 解决方案 > Workbox 运行时缓存不适用于带有查询参数的 url?

问题描述

我有一个像这样的公共 API 端点:

https://data.weather.gov.hk/weatherAPI/opendata/weather.php?dataType=warnsum&lang=en

我想用服务工作者运行时缓存它的响应。这就是我定义路线的方式:

registerRoute(
  new RegExp('.+/weatherAPI/opendata/weather.php?dataType=warnsum&lang=en'),
  new StaleWhileRevalidate({
    cacheName: 'weatherApi',
    plugins: [
      new ExpirationPlugin({
        maxAgeSeconds: 60 * 60 * 24
      }),
      new BackgroundSyncPlugin('getWeatherAPI', {
        maxRetentionTime: 24 * 60 // Retry for max of 24 Hours (specified in minutes)
      })
    ]
  })
)

但是,这不起作用,并且此 url 的响应未保存到缓存中。我想知道查询参数是否会成为这里的问题,或者我是否遗漏了什么?

标签: javascriptprogressive-web-appsworkbox

解决方案


RegExpRoute在 Workbox 中执行匹配时会包含查询参数。

我认为您更有可能需要转义正则表达式中“特殊”的字符,例如?.

使用正则表达式以外的东西实际上可能更容易。例如,您可以使用 a matchCallback,例如:

registerRoute(
  ({url}) => url.href.endsWith('/weatherAPI/opendata/weather.php?dataType=warnsum&lang=en'),
  new StaleWhileRevalidate({...}),
)

推荐阅读