Failed to register a ServiceWorker: A bad HTTP response code (404) was received when fetching the script

22,620

Solution 1

you could use the full url path for the registration for example:

navigator.serviceWorker.register('ScriptsFolder/subFolder/sw.js')

Solution 2

The only way I have found to solve the TypeError issue when starting a nodejs service worker is to put the service worker script in the root directory of your application, in my case the root of my Amazon EC2 web server.

Wish the error message was more descriptive, TypeError is not terribly helpful. But this fix worked for me.

Share:
22,620
f.c
Author by

f.c

an engineer enjoys learning computer science.

Updated on October 15, 2020

Comments

  • f.c
    f.c over 3 years

    I am creating a progressive web application (pwa) and try to register service worker to test offline feature. The folder structure is like below:

    -- views 
       -- index.pug
    -- sw.js
    -- public
       -- js
          -- main.js
    -- index.js
    

    index.js file is server file, main.js is the file that being link in each .pug file. I embedded the service worker register code in, the code is like following

    if ('serviceWorker' in navigator) {
        window.addEventListener('load', function() {
            navigator.serviceWorker.register('./sw.js').then(function(registration) {
                // Registration was successful
                console.log('Service Worker registration successful with scope: ', registration.scope);
    
                // console.log('Service Worker registration successful with scope: ', registration.scope);
            }, function(err) {
                // registration failed :(
                console.log('ServiceWorker registration failed: ', err);
            });
        });
    }
    

    The 404 error keeps pop up in localhost also the deployed URL which I have no clue why, how to solve this?

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

    Thanks

    Solutions (UPDATE) -

    Include app.use('/', routes) ,or wherever the service-worker file at into index.js file.