簡體   English   中英

努力理解為什么我的服務人員不工作 - 未捕獲(承諾)類型錯誤:請求失敗

[英]Struggling with understanding why my service worker isnt working - Uncaught (in promise) TypeError: Request failed

我一直按照https://www.pwabuilder.com上的說明使我的網站可以離線使用。 在控制台日志中,我收到說明 PWA 已安裝並離線緩存的消息,但標題中出現錯誤。

我去過許多 stackoverflow 線程和其他網站,但我沒有嘗試任何工作。 這不是我的強項,我是一名 UX/UI 設計師,可以編寫簡單的 static 頁面,但目前這比我的技能水平略高。

我真的很難弄清楚如何解決這個問題,因為(對我來說)這個錯誤非常模糊。 我假設它是我錯過的一些簡單的東西。 站點 url 是https://ovoc.netlify.com/但我還將在下面鏈接清單和服務人員

manifest.json

{
    "dir": "ltr",
    "lang": "en",
    "name": "Our voice our community | Get involved in de…",
    "scope": "/",
    "display": "fullscreen",
    "start_url": "https://ovoc.netlify.com/",
    "short_name": "OVOC",
    "theme_color": "transparent",
    "description": "Our voice our community is a project run by BGC Wales to empower young people to engage in community decision making",
    "orientation": "any",
    "background_color": "transparent",
    "related_applications": [],
    "prefer_related_applications": false,
    "icons": [{
    "src": "assets/icons/logo.png",
    "sizes": "192x192",
    "type": "image/png"
  }]
}

這是服務人員

// This is the "Offline copy of pages" service worker

const CACHE = "pwabuilder-offline";

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

// Install stage sets up the index page (home page) in the cache and opens a new cache
self.addEventListener("install", function (event) {
  console.log("[PWA Builder] Install Event processing");

  event.waitUntil(
    caches.open(CACHE).then(function (cache) {
      console.log("[PWA Builder] Cached offline page during install");

      if (offlineFallbackPage === "index.html") {
        return cache.add(new Response("TODO: Update the value of the offlineFallbackPage constant in the serviceworker."));
      }

      return cache.add(offlineFallbackPage);
    })
  );
});

// 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;

  event.respondWith(
    fetch(event.request)
      .then(function (response) {
        console.log("[PWA Builder] add page to offline cache: " + response.url);

        // 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) {
  return caches.open(CACHE).then(function (cache) {
    return cache.put(request, response);
  });
}

我真的很掙扎,我的客戶是一個慈善機構,所以我真的很想為他們做這項工作,任何幫助將不勝感激!

如果您訪問https://ovoc.netlify.com/ ,您應該在 Chrome DevTools 的 Network 面板中看到以下內容:

網絡面板截圖

這表明 SW 正在請求 URL https://ovoc.netlify.com/[object%20Response] ,返回 404 響應。

它還告訴您此請求源自pwabuilder-sw.js:17 ,即您的服務工作者腳本的第 17 行。

該行對應於:

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

這似乎是您需要更新的一些占位符代碼,以便為離線頁面放入實際的 URL。

此外,您的<head>的標簽包含許多undefined的 URL:

在此處輸入圖像描述

看起來這些是由ManUp.js生成的,因此您應該確保正確配置它。

@AdamElsbury, here is the working code for caching static assets and dynamic assets in your application Note: 1) when installing service worker it installs all the static html, css, js files 2) Replace all the static file names with the files available in您的應用程序 3) 動態緩存用於緩存頻繁更新的圖像 4) 如果您發布需要更新給用戶的新版本,只需將 CACHE_STATIC_NAME 更改為 1 版本

var CACHE_STATIC_NAME = 'static-v1';
var CACHE_DYNAMIC_NAME = 'dynamic-v1';

self.addEventListener('install', function(event) {
  console.log('[Service Worker] Installing Service Worker ...', event);
  event.waitUntil(
    caches.open(CACHE_STATIC_NAME)
      .then(function(cache) {
        console.log('[Service Worker] Precaching App Shell');
        cache.addAll([
          '/',
          '/index.html',
          '/src/js/app.js',
          '/src/js/feed.js',
          '/src/js/promise.js',
          '/src/js/fetch.js',
          '/src/js/material.min.js',
          '/src/css/app.css',
          '/src/css/feed.css',
          '/src/images/main-image.jpg',
          'https://fonts.googleapis.com/css?family=Roboto:400,700',
          'https://fonts.googleapis.com/icon?family=Material+Icons',
          'https://cdnjs.cloudflare.com/ajax/libs/material-design-lite/1.3.0/material.indigo-pink.min.css'
        ]);
      })
  )
});

self.addEventListener('activate', function(event) {
  console.log('[Service Worker] Activating Service Worker ....', event);
  event.waitUntil(
    caches.keys()
      .then(function(keyList) {
        return Promise.all(keyList.map(function(key) {
          if (key !== CACHE_STATIC_NAME && key !== CACHE_DYNAMIC_NAME) {
            console.log('[Service Worker] Removing old cache.', key);
            return caches.delete(key);
          }
        }));
      })
  );
  return self.clients.claim();
});

self.addEventListener('fetch', function(event) {
  event.respondWith(
    caches.match(event.request)
      .then(function(response) {
        if (response) {
          return response;
        } else {
          return fetch(event.request)
            .then(function(res) {
              return caches.open(CACHE_DYNAMIC_NAME)
                .then(function(cache) {
                  cache.put(event.request.url, res.clone());
                  return res;
                })
            })
            .catch(function(err) {

            });
        }
      })
  );
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM