Service-Worker,"TypeError:请求<anonymous>失败"

Max*_*Web 7 html basic-authentication browser-cache http-status-code-401 service-worker

我希望你能解决我的问题.目前,我与服务工作者建立了PWA.它注册成功,但安装有问题.

"caches.open"-promise会导致错误:"TypeError:Request failed at".您可以在Chrome中看到缓存已注册,但为空.我已经检查了缓存网址数千次..

这是我的服务工作者代码

var CACHE_NAME = 'surv-cache-1';

var resourcesToCache = [
    '/',
    '/index.html',
    '/jquery-3.2.1.min.js',
    '/pouchdb.min-6.4.1.js',
    '/styles/inline.css',
    '/scripts/app.js'
];

self.addEventListener('install', function(event) {
  event.waitUntil(
    // open the app browser cache
    caches.open(CACHE_NAME).then(function(cache) {
        console.log("Install succesfull");
        // add all app assets to the cache
        return cache.addAll(resourcesToCache);
    }).then(function(out){
        console.log(out);
    }).catch(function(err){
        console.log(err);
    })
  );
});

self.addEventListener('fetch', function(event) {
  event.respondWith(
    // try to find corresponding response in the cache
    caches.match(event.request)
      .then(function(response) {
        if (response) {
          // cache hit: return cached result
          return response;
        }

        // not found: fetch resource from the server
        return fetch(event.request);
      }).catch(function(err){
          console.log(err);
      })
  );
});
Run Code Online (Sandbox Code Playgroud)

我的注册码:

<script>
    if ('serviceWorker' in navigator) {
        navigator.serviceWorker.register('service-worker.js').then(function(registration) {
            console.log('Service worker registered:'+registration.scope);
        }).catch(function(e) {
            console.log(e);
        });
    };
Run Code Online (Sandbox Code Playgroud)

我没有得到它..我希望你有一个想法:)

编辑:我想我现在知道为什么它不起作用.我对我的域名进行了身份验证,因此并非每个人都可以访问它.当我的服务工作者想要缓存数据时,它会恢复401.所以它似乎是身份验证的问题.

也许有人已经有同样的问题?

Okk*_*kku 8

当您resourcesToCache包含返回404响应的内容时,就会发生这种情况。确保正确键入所有内容。还要确保范围正确。您可以使用以下方法检查工作范围:

if("serviceWorker" in navigator) {
  navigator.serviceWorker
  .register(`worker.js`)
  .then(registration => {
    console.log("SW scope:", registration.scope);
  });
}
Run Code Online (Sandbox Code Playgroud)

如果您的项目不在服务器域根目录中,则执行以下操作可能会有所帮助:

//your main js
if("serviceWorker" in navigator) {
  navigator.serviceWorker
  .register(`${window.location.pathname}worker.js`)
  .then(registration => {
    //do your thing
  });
}


//your worker js
let resourcesToCache = [
  './',
  './index.html',
  './jquery-3.2.1.min.js',
  './pouchdb.min-6.4.1.js',
  './styles/inline.css',
  './scripts/app.js',
];
//...
Run Code Online (Sandbox Code Playgroud)

附带说明一下,您应该从CDN加载您的库(jQuery,pouchdb)以提高性能。那些也可以被缓存:

let resourcesToCache = [
  './',
  './index.html',
  'https://code.jquery.com/jquery-3.3.1.min.js',
  'https://cdnjs.cloudflare.com/ajax/libs/pouchdb/6.4.3/pouchdb.min.js',
  './styles/inline.css',
  './scripts/app.js',
];
Run Code Online (Sandbox Code Playgroud)