Uncaught (in promise) TypeError: Failed to execute 'Cache' on 'addAll': Request failed on progressive web app

Uncaught (in promise) TypeError: Failed to execute 'Cache' on 'addAll': Request failed on progressive web app

我正在学习一个简单的 PWA 教程,但是当我完成它时,我收到以下控制台错误,

Uncaught (in promise) TypeError: Failed to execute 'Cache' on 'addAll': Request failed

这是我的 serviceworker 文件

const staticDevCoffee = "dev-coffee-site-v1"
const assets = [
  "/",
  "/test.html",
  "/csstest/style.css",
  "/jstest/app.js",
  "/coffee.png",
]

self.addEventListener("install", installEvent => {
  installEvent.waitUntil(
    caches.open(staticDevCoffee).then(cache => {
      cache.addAll(assets)
    })
  )
})

当我 运行 灯塔测试时,我明白了,

start_url does not respond with a 200 when offlineThe start_url did respond, but not via a service worker.

这是我第一次看到 PWA,所以我有点卡住了。我尝试了在 SO 上找到的几种解决方案,但 none 有效。

  • 对于第一个例外:-

    未捕获(承诺)TypeError:无法在 'addAll' 上执行 'Cache':请求失败

当您在缓存列表中提到的任何文件 return 收到 404 响应时,您会收到此异常。因此,请确保所有资源都提供 200。

  • 对于第二个错误:-

    start_url 离线时不响应 200start_url 响应。

在您的情况下,由于文件未被缓存(由于第一个异常),您会收到此错误并确保在缓存列表中缓存根索引文件。

self.addEventListener("install", (event) => {
    console.log("Service Worker : Installed!")

    event.waitUntil(
        
        (async() => {
            try {
                cache_obj = await caches.open(cache)
                cache_obj.addAll(caching_files)
            }
            catch{
                console.log("error occured while caching...")
            }
        })()
    )
} )

这段代码对我有用!