首页 > 解决方案 > 在 Cache API 中,使用 caches.match(event.request) 和 caches.match(event.request.url) 有什么区别

问题描述

我正在与服务人员一起工作,我有以下代码

  self.addEventListener('fetch', function (event) {
    const url = new URL(event.request.url)

    if (event.request.mode == "navigate") {
        const fetchData = fetch(event.request).catch(function () {
            //console.log("errr")
            return caches.match("/core/index.php/offline_controlador/index")
        });
        event.respondWith(fetchData)
        return;
    }

    event.respondWith(
        caches.match(event.request).then(function (response) {
            return response || fetch(event.request);
        })
    );
 });

当我试图从缓存中获取这些文件时,它不起作用,但是当我将代码更改为

event.respondWith(
        caches.match(event.request.url).then(function(response) {
          return response || fetch(event.request);
        })
    );

代替

event.respondWith(
            caches.match(event.request).then(function(response) {
              return response || fetch(event.request);
            })
        );

它完美无缺

标签: javascriptservice-workerprogressive-web-appscacheapi

解决方案


Cache Storage API 规范的相关部分是5.4.2。(虽然这适用于对象的matchAll()方法,Cache但当你这样做时,这最终被称为“幕后” caches.match()

与您的问题特别相关的是第 2 步:

如果可选参数 request 没有被省略,那么:

  • 如果request是一个Request对象,那么:

    • 设置rrequest的请求。

    • 如果r' 的方法不是GET并且options.ignoreMethod为假,则返回一个用空数组解析的承诺。

  • 否则,如果 request 是一个字符串,那么:

    • 设置为调用as 构造函数r的初始值并作为其参数的结果的关联请求。如果这引发异常,则返回一个因该异常而被拒绝的承诺。Requestrequest

总而言之,最大的区别在于,如果传入一个Request对象作为第一个参数可能会导致match()失败,如果Request有 amethod以外的东西'GET'。也许这就是你遇到的。

除此之外,这两种方法应该基本相同,尽管传入 aRequest稍微更有效,因为浏览器不必Request基于字符串隐式创建对象。


推荐阅读