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

5.2k views Asked by At

I'm trying to add a service worker to a website.I'm using Node.js with Express.js,Vue.js and EJS.^

My node server (index.js) looks like :

const https = require('https');
const fs = require('fs');
const express = require('express');
const app = express();
const router = express.Router();
const pool = require('./mysqldb.js');
const pathView = __dirname + "/views/";
var bodyParser = require("body-parser");
const listenPort = 8010;

// Process application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: true }));

// Process application/json
app.use(bodyParser.json());

app.set('view engine', 'ejs');

app.use(express.static('public'));
app.use('/public', express.static('public'));


router.use(function (req, res, next) {
  next();
});

// home
router.get('/', function (req, res) {
   res.render( 'home.ejs', { msg:" > "  });
});

app.use( "/", router);

// Not found
app.use("*",function(req,res){
res.setHeader('Content-Type', 'text/html');
res.status(404).send('Page introuvable !');
});

// Run server
app.listen(listenPort, function () {
  console.log('Example app listening on port ' + listenPort )
});

And the home.ejs file looks like:

<!DOCTYPE html>
<html lang="en">

<body>

<script>
   if ('serviceWorker' in navigator) {
          navigator.serviceWorker.register('ServiceWorker.js').then(function(registration)     {
  console.log('ServiceWorker registration successful with scope: ', registration.scope);
    }).catch(function(err) {
      //registration failed :(
      console.log('ServiceWorker registration failed: ', err);
    });
  }else {
    console.log('No service-worker on this browser');}
</script>

</body>
    </html>

I have to mention that I'm testing it on https. I don't think the content of ServiceWorker.js is that importat,but if you would need it to help me I can post it too. The server files scheme would look like:

  index.js
  mysqldb.js
  public //(folder)
  views /*(folder)*/ : home.ejs , ServiceWorker.js

And when I open the website on https I get the following error in web console:

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

There are 1 answers

0
abraham On

ServiceWorker.js is in your views folder. That is for templates that get rendered by express as a page. Move it to public so that it gets served like a static file.