简体   繁体   English

React Service Worker fetch事件侦听器永远不会为外部API请求执行

[英]React Service Worker fetch event listener never executes for external API requests

I'm creating a PWA using React. 我正在使用React创建一个PWA

My Service Worker seems to be working fine except for the fetch event listener, which does not execute when a GET HTTP request fires within my React app using the fetch API to get data from an external API on the web. 我的服务工作者似乎工作正常,除了fetch事件监听器,当使用fetch API在我的React应用程序中触发GET HTTP请求以从Web上的外部API获取数据时,该监听器不会执行。

Where should I be placing my fetch event listener? 我应该在哪里放置我的fetch事件监听器?

Does it work for external requests or only for requests to files that are part of the app? 它适用于外部请求还是仅适用于属于应用程序一部分的文件的请求?
Please let me know if you notice any issues with my code below. 如果您发现我的代码存在任何问题,请通知我。

I'm using the boilerplate Service Worker file that comes when using create-react-app to start a new project. 我正在使用使用create-react-app启动新项目时出现的样板文件Service Worker文件。


Here is my code: 这是我的代码:

(The execution never gets into the window.addEventListener('fetch', ...) part) (执行永远不会进入window.addEventListener('fetch', ...)部分)

function registerValidSW(swUrl) {
  navigator.serviceWorker
    .register(swUrl)
    .then(registration => {
      registration.onupdatefound = () => {
        const installingWorker = registration.installing;
        installingWorker.onstatechange = () => {
          if (installingWorker.state === 'installed') {
            if (navigator.serviceWorker.controller) {

              window.addEventListener('fetch', (event) => {
                event.respondWith(
                  caches.match(event.request)
                    .then((response) => {
                      if (response) {
                        return response
                      }
                      return fetch(event.request).then(response => { 
                        caches.open('fetch').then((cache) => {
                          cache.put(event.request, response.clone());
                        });
                        return response;
                      })
                    }
                  )
                );
              });

              console.log('New content is available; please refresh.');
            } else {
              // static files caching
              cacheStaticFiles();

              // external api data caching
              cacheApiData();

              // At this point, everything has been precached
              console.log('Content is now cached for offline use.');
            }
          }
        };
      };
    })
    .catch(error => {
      console.error('Error during service worker registration:', error);
    });
}

So I ran into this issue. 所以我遇到了这个问题。 It turns out that CRA actually compiles that service worker into a different service-worker.js file in your build folder, and that gets registered. 事实证明,CRA实际上将该服务工作者编译到构建文件夹中的另一个service-worker.js文件中,然后进行注册。 If you append your code to the end of that file it will work, but annoyingly you'd have to do that on every build. 如果将代码附加到该文件的末尾,它将起作用,但令人烦恼的是,您必须在每次构建时都这样做。

I'm using this addin: https://www.npmjs.com/package/cra-append-sw to append it automatically instead. 我正在使用这个插件: https ://www.npmjs.com/package/cra-append-sw自动附加它。

At present it had this minor issue, which requires running it with a different option: https://github.com/tszarzynski/cra-append-sw/issues/18 目前它有这个小问题,需要使用不同的选项运行它: https//github.com/tszarzynski/cra-append-sw/issues/18

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM