I'm looking for an answer to my problem. I'm testing service worker of workbox with my nodeJs server. I tested with basic configuration like below :
Basic nodeJs app.js
var http = require('http');
var fs = require('fs');
var server = http.createServer(function (req, res) {
if (req.url === "/") {
fs.readFile('index.html', function (err, data) {
if (err) throw err
res.writeHead(200, {
'Content-type': 'text/html;charset=utf-8'
});
res.end(data);
});
} else if (req.url === '/sw.js') {
fs.readFile('sw.js', function (err, data) {
if (err) throw err
res.writeHead(200, {
'Content-type': 'text/javascript'
});
res.end(data);
});
}
});
server.listen(8080);
I managed to put my files into the cache and to make it work in offline mode. But, problems started when I tried to use Express module :
Express nodeJs app.js
var express = require('express');
var app = express();
app.listen(8080);
//*****************************************************************
//-------------------------- TEMPLATES --------------------------
//*****************************************************************
//moteur de modèles ou de templates
app.set('view engine', 'ejs');
//*****************************************************************
//-------------------------- MIDDLEWARE --------------------------
//*****************************************************************
app.use('/static', express.static(__dirname + '/public'));
//*****************************************************************
//--------------------------- ROUTES ------------------------------
//*****************************************************************
app.get('/', function (request, response) {
response.render('./pages/index.ejs');
});
I manage to put my files into the cache but, I don't manage to make it work in offline mode. What is the reason of this difference ?
sw.js
importScripts('https://storage.googleapis.com/workbox-cdn/releases/3.4.1/workbox-sw.js');
if (workbox) {
console.log(`Yay! Workbox is loaded `);
} else {
console.log(`Boo! Workbox didn't load `);
}
workbox.precaching.precacheAndRoute([
{ url: '/', revision: '383676' }
]);
+-node_modules
+-public
+-js
sw-register.js
sw.js
+-css
+-views
+-pages
index.ejs
server.js
EDIT
Don't ask me why, but the problem solved when I added this piece of code into my app.js file, middelware session :
app.use(express.static(__dirname + '/views/pages'));
and inside my "pages" folder I put my sw.js file. In fact, no matter where I put my sw.js file as long as it is inside the folder target by the _dirname.