serviceworker中获取页面和文件的区别

difference between fetching page and file in serviceworker

    event.respondWith(caches.match(event.request).then(function (response) {
        if (response) {
            return response;
        }          
         //return fetch(event.reuqest, { credentials: 'include' });

        //event.respondWith(fetch(event.request, { credentials: 'include' }));
    }));

这是通过 serviceworkers 处理请求的通用代码,如果 url 在缓存中,则 return 缓存响应或从服务器获取它。 但我的疑问是关于 2 行注释,我们需要使用其中之一来获取响应。

我的疑问是,当我使用 event.respondWith(fetch(event.request, { credentials: 'include' 获取页面时,出现以下错误

DOMException: Failed to execute 'respondWith' on 'FetchEvent': The fetch event has already been responded to.

但是页面终于呈现了,肯定浏览器终于​​获取了响应,但是当我使用 sam 获取图像时,我得到了同样的错误,最重要的是图像没有被获取。

如果我使用第二个选项 return fetch(event.reuqest, { credentials: 'include' }); ,那么它对图像和页面都适用。

我无法弄清楚该错误的原因是什么,以及文件和页面的行为不同的原因。

我的另一个疑问是,我真的需要这里的凭据参数吗,我添加它是因为我在网络上看到的大多数实现都使用了它,但我观察到的是请求对象已经有一个凭据属性 有了它,现在不总是

include

有时候是

same-origin

也是。 那么有没有可能我实际上通过添加它来覆盖实际的凭证值。如果不是这种情况,那么包括它没有区别或者 not.It 无关紧要。

但如果是其他方式,那么我们不应该覆盖凭证值,这可能会产生不良的副作用。

您已经调用了 event.respondWith,您不需要调用它两次。

您的第一个调用将使用返回的承诺:

caches.match(event.request).then(function(response) {
  if (response) {
    return response;
  }

  return fetch(event.reuqest, { credentials: 'include' });
})

此承诺解析为:

  • response,如果请求在缓存中;
  • 调用 fetch 返回的承诺,否则。

fetch 返回的承诺将解析为响应,然后将由 respondWith 使用。