Ciprian
Ciprian

Reputation: 3226

Angular 2 - Service worker not found - A bad HTTP response code (404)

I used sw-precache to generate a service worker for a Firebase hosted Angular 2 app.

Error:

Service Worker registration failed:  TypeError: Failed to register a ServiceWorker: A bad HTTP response code (404) was received when fetching the script.

Structure

src-
  app--
     index.html    
service-worker.js
sw-precache-config.js

sw-precache-config.js

module.exports = {
  navigateFallback: '../index.html',
  stripPrefix: 'dist',
  root: 'dist/',
  staticFileGlobs: [
    'dist/index.html',
    'dist/**.js',
    'dist/**.css'
  ]
};

index.html

<script>
    if ('serviceWorker' in navigator) {
      console.log(navigator.serviceWorker);

      navigator.serviceWorker.register('service-worker.js').then(function (registration) {
        console.log('Service Worker registered');
      }).catch(function (err) {
        console.log('Service Worker registration failed: ', err);
      });
    }
  </script>

Upvotes: 5

Views: 3468

Answers (1)

wakarK
wakarK

Reputation: 36

Your service worker registration code seems fine to me.The problem might be in the project structure.Since you have mentioned the root as dist folder, your service-worker.js file must be in the dist folder after you run the ng build script. Add "precache": "sw-precache --verbose --config=sw-precache-config.js" to your package.json scripts object.Then run: ng build --prod --aot,then npm run precache.Now your service-worker.js file would be present in the dist folder.Since the angular compiler has compiled your app code into js files and stored it in the dist folder ,now you must serve your app from the dist folder.But the default ng serve doesn't support it.I suggest you to use http-server. npm install http-server -g.Then http-server ./dist -o.This open up your app on default browser.

Upvotes: 1

Related Questions