How to make workbox cache cross origin responses?

随声附和 提交于 2019-12-11 08:07:25

问题


According to workbox doc, cross domain request should be configured to ensure that regular expression matches the beginning of the URL. However, it doesn't work.

The service worker code is like below.

importScripts('https://storage.googleapis.com/workbox-cdn/releases/3.0.0/workbox-sw.js');

workbox.routing.registerRoute(
  /.*\.(png|jpg|jpeg|svg|gif)/,
  workbox.strategies.cacheFirst()
);

workbox.routing.registerRoute(
  new RegExp('^https://a248.e.akamai.net/.*'),
  workbox.strategies.cacheFirst()
);

In the page, responses from same origin resources are cached, but responses from https://a248.e.akami.net is not.

Anything wrong with my config? or is this a workbox 3.0.0 bug?


回答1:


Do you have CORS enabled on your https://a248.e.akami.net server? If not, you'll be getting back opaque responses, and by default, those will not be cached when using a cacheFirst strategy.

There's a guide for handling third-party requests with a recipe you could use if you want to opt-in to caching those responses when using a cacheFirst strategy:

workbox.routing.registerRoute(
  new RegExp('^https://a248.e.akamai.net/.*'),
  workbox.strategies.cacheFirst({
    plugins: [
      new workbox.cacheableResponse.Plugin({
        statuses: [0, 200]
      })
    ]
  }),
);

You should also see a new warning logged in the JavaScript console when using Workbox v3 in localhost when this situation arises, explaining what's going on.



来源:https://stackoverflow.com/questions/49295757/how-to-make-workbox-cache-cross-origin-responses

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!