Uncaught (in promise) TypeError: Request failed

孤者浪人 提交于 2019-12-04 23:12:17

Remove this line:

<script src="serviceworker.js"></script>

You're not supposed to include your SW as a script in the page. You're only supposed to interact with it by calling the navigator.serviceWorker.register() as you do in your script above.

Lighthouse is not reporting it but I'm making sure: you're serving the website overt HTTPS right?

I had a typo in one of the filenames that I had added to cached_urls. It did not match the name of the real file so I kept getting the error

I found it by quickly setting cached_urls to an empty list and found that the error went away.

Add '/'. Your cached_urls members require you to include the slash sign:

var cached_urls = [
  '/offline.html',
  '/fourohfour.html',
  '/account.html',
  '/altontowers.html',
  '/bet365.html',
  '/booking-altonTowers.html',
  '/booking-manchesterAirport.html',
  '/booking-northStaffsHotel.html',
  '/bookings.html',
  '/emmabridgewater.html',
  '/freeportTalke.html',
  '/index.html',
  '/intupotteries.html',
  '/search.html',
  '/trenthamEstate.html',
  '/style.css'
];

I had the same error. The error log is very succint but as previously mentionned, it is very likely to originate from failed request from the service worker to request page from the server.

The trick is to understand the service worker scope. By default, its scope is the directory it's in. If you access your service worker script from https://your.domain.com/static/service-worker.js, its default scope will be /static. So, if you type cache.add('index.html'), it will actually request https://your.domain.com/static/index.html, which will result in an error if you were trying to get https://your.domain.com/index.html. Two solutions:

  • Access files using relative paths: cache.add('../index.html')
  • Change the scope when registering:
    • Use navigator.serviceWorker.register('static/service-worker.js', {scope: '/'})
    • Add the HTTP header Service-Worker-Allowed: / when serving your website
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!