首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用微软的pwa-builder : Uncaught (in promise) TypeError:请求失败

使用微软的pwa-builder : Uncaught (in promise) TypeError:请求失败
EN

Stack Overflow用户
提问于 2019-07-04 17:59:31
回答 2查看 955关注 0票数 0

我想使用服务工作者来缓存文件,并通过提供脱机页面来改善用户体验。我使用pwabuilder.com为网站创建文件。不幸的是,即使在使用不带任何元素的代码进行缓存时,它也会发出错误"Uncaught (in promise) TypeError: Request failed“

我仔细检查了代码,尝试了Google Developper和Stackoverflow上显示的不同错误修复,但这些都不能帮助我修复问题。

我在HTML文件中有以下内容:

代码语言:javascript
复制
if ("serviceWorker" in navigator) {
      if (navigator.serviceWorker.controller) {
        console.log("[PWA Builder] active service worker found, no need to register");
      } else {
        // Register the service worker
        navigator.serviceWorker
          .register("pwabuilder-sw.js", {
            scope: "./"
          })
          .then(function (reg) {
            console.log("[PWA Builder] Service worker has been registered for scope: " + reg.scope);
          });
      }
}

服务工作者注册成功。

pwabuilder-sw.js是这样的:

代码语言:javascript
复制
//This is the service worker with the Advanced caching



    const CACHE = "pwabuilder-adv-cache";

    const precacheFiles = [

      /* Add an array of files to precache for your app */
        '/cms/stylesheets/bootstrap.css',
        '/cms/stylesheets/ifpayroll.css',
        '/cms/stylesheets/animate.css',
        '/cms/stylesheets/fontawesome-webfont.css',
        '/cms/javascript/main.js',
        '/cms/javascript/aos.js',
        '/cms/images/logo@3x.png',
    ];



    // TODO: replace the following with the correct offline fallback page i.e.: const offlineFallbackPage = "offline.html";

    const offlineFallbackPage = "ToDo-replace-this-name.html";



    const networkFirstPaths = [

      /* Add an array of regex of paths that should go network first */

      // Example: /\/api\/.*/

    ];



    const avoidCachingPaths = [

      /* Add an array of regex of paths that shouldn't be cached */

      // Example: /\/api\/.*/

    ];



    function pathComparer(requestUrl, pathRegEx) {

      return requestUrl.match(new RegExp(pathRegEx));

    }



    function comparePaths(requestUrl, pathsArray) {

      if (requestUrl) {

        for (let index = 0; index < pathsArray.length; index++) {

          const pathRegEx = pathsArray[index];

          if (pathComparer(requestUrl, pathRegEx)) {

            return true;

          }

        }

      }



      return false;

    }



    self.addEventListener("install", function (event) {

      console.log("[PWA Builder] Install Event processing");



      console.log("[PWA Builder] Skip waiting on install");

      self.skipWaiting();



      event.waitUntil(

        caches.open(CACHE).then(function (cache) {

          console.log("[PWA Builder] Caching pages during install");



          return cache.addAll(precacheFiles).then(function () {

            if (offlineFallbackPage === "ToDo-replace-this-name.html") {

              return cache.add(new Response("TODO: Update the value of the offlineFallbackPage constant in the serviceworker."));

            }



            return cache.add(offlineFallbackPage);

          });

        })

      );

    });



    // Allow sw to control of current page

    self.addEventListener("activate", function (event) {

      console.log("[PWA Builder] Claiming clients for current page");

      event.waitUntil(self.clients.claim());

    });



    // If any fetch fails, it will look for the request in the cache and serve it from there first

    self.addEventListener("fetch", function (event) {

      if (event.request.method !== "GET") return;



      if (comparePaths(event.request.url, networkFirstPaths)) {

        networkFirstFetch(event);

      } else {

        cacheFirstFetch(event);

      }

    });



    function cacheFirstFetch(event) {

      event.respondWith(

        fromCache(event.request).then(

          function (response) {

            // The response was found in the cache so we responde with it and update the entry



            // This is where we call the server to get the newest version of the

            // file to use the next time we show view

            event.waitUntil(

              fetch(event.request).then(function (response) {

                return updateCache(event.request, response);

              })

            );



            return response;

          },

          function () {

            // The response was not found in the cache so we look for it on the server

            return fetch(event.request)

              .then(function (response) {

                // If request was success, add or update it in the cache

                event.waitUntil(updateCache(event.request, response.clone()));



                return response;

              })

              .catch(function (error) {

                // The following validates that the request was for a navigation to a new document

                if (event.request.destination !== "document" || event.request.mode !== "navigate") {

                  return;

                }



                console.log("[PWA Builder] Network request failed and no cache." + error);

                // Use the precached offline page as fallback

                return caches.open(CACHE).then(function (cache) {

                  cache.match(offlineFallbackPage);

                });

              });

          }

        )

      );

    }



    function networkFirstFetch(event) {

      event.respondWith(

        fetch(event.request)

          .then(function (response) {

            // If request was success, add or update it in the cache

            event.waitUntil(updateCache(event.request, response.clone()));

            return response;

          })

          .catch(function (error) {

            console.log("[PWA Builder] Network request Failed. Serving content from cache: " + error);

            return fromCache(event.request);

          })

      );

    }



    function fromCache(request) {

      // Check to see if you have it in the cache

      // Return response

      // If not in the cache, then return error page

      return caches.open(CACHE).then(function (cache) {

        return cache.match(request).then(function (matching) {

          if (!matching || matching.status === 404) {

            return Promise.reject("no-match");

          }



          return matching;

        });

      });

    }



    function updateCache(request, response) {

      if (!comparePaths(request.url, avoidCachingPaths)) {

        return caches.open(CACHE).then(function (cache) {

          return cache.put(request, response);

        });

      }



      return Promise.resolve();

    } 

除了已添加的缓存文件外,它与pwabuilder.com上提供的完全相同。

代码语言:javascript
复制
Manifest: unknown 'orientation' value ignored.
pwabuilder-sw.js:83 [PWA Builder] Install Event processing
pwabuilder-sw.js:87 [PWA Builder] Skip waiting on install
pwabuilder-sw.js:97 [PWA Builder] Caching pages during install
legal.html:63 [PWA] Service worker has been registered for scope: https://www.ifpayroll.lu/
pwabuilder-sw.js:1 Uncaught (in promise) TypeError: Request failed

这就是我得到的。

EN

回答 2

Stack Overflow用户

发布于 2019-07-29 17:57:44

您必须更改此行以反映您的真实文件名,并确保该文件存在:

代码语言:javascript
复制
const offlineFallbackPage = "ToDo-replace-this-name.html";

然后,您还可以删除以下行:

代码语言:javascript
复制
       if (offlineFallbackPage === "ToDo-replace-this-name.html") {

          return cache.add(new Response("TODO: Update the value of the offlineFallbackPage constant in the serviceworker."));

        }
票数 2
EN

Stack Overflow用户

发布于 2020-05-11 12:57:51

脱机回退页指令的文档记录很糟糕,令人讨厌。

可以删除这些行:

代码语言:javascript
复制
       if (offlineFallbackPage === "ToDo-replace-this-name.html") {

          return cache.add(new Response("TODO: Update the value of the offlineFallbackPage constant in the serviceworker."));

        }
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56885426

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档