Home > Enterprise >  How to add PWA functionality to a express web app
How to add PWA functionality to a express web app

Time:12-17

I am currently trying to add PWA integration to a web app. I have created a manifest.json and added it to the head of my page, and that is loading fine, however the serviceworker registered in my app.js doesnt seem to be doing anything.

Below is the section of code I am using to set up the app:

const express = require("express")
const path = require('path')
const chalk = require('chalk')
const debug = require('debug')('app')
const morgan = require('morgan')
const sql = require('mssql')
const navigator = require('navigator')
const https = require('https')
const fs = require('fs')

const app = express()
const viewsPath = path.join(__dirname "/src/views/")
const routesPath = path.join(__dirname "/src/routes/")
const publicPath = path.join(__dirname "/public/")
const modulePath = path.join(__dirname '/node_modules/')
const port = process.env.PORT || 443

const alcoholRouter = require(routesPath 'alcoholRoutes.js')
const cocktailRouter = require(routesPath 'cocktailRoutes.js')
const mixerRouter = require(routesPath 'mixerRoutes.js')

app.use(morgan('tiny'))
app.use(express.static(publicPath))
app.use('/css', express.static(modulePath 'bootstrap\\dist\\css'))
app.use('/js', express.static(modulePath 'bootstrap\\dist\\js'))
app.use('/js', express.static(modulePath 'jquery\\dist'))
app.set('views', viewsPath)
app.set('view engine', process.env.ENGINE || "ejs")
app.use('/alcohol', alcoholRouter)
app.use('/cocktails', cocktailRouter)
app.use('/mixers', mixerRouter)

app.get('/', function(req, res){
    res.render('index', {
        nav:  [
            {link: '/alcohol', title: 'Alcohol'},
            {link: '/cocktails', title: 'Cocktails'},
            {link: '/mixers', title: 'Mixers'}
        ],
        title: 'BarCart'
    })
})

https.createServer(
    {
        key:fs.readFileSync('44400120_localhost.key'),
        cert:fs.readFileSync('44400120_localhost.cert'),
    }, app).listen(port, function(){
        debug(`Listening on port ${chalk.greenBright(port)}`)
    }
)

app.get('*', function(req, res){
    res.redirect('https://'   req.headers.host   req.url)
})

app.listen(80)

if('serviceWorker' in navigator){
    navigator.serviceWorker.register('sw.js')
}

This is the code for my serviceworker

var contentToCache = [
    './',
    'src/views/alcoholListView.ejs',
    'src/views/cocktailListView.ejs',
    'src/views/mixerListView.ejs',
    'src/views/alcoholView.ejs',
    'src/views/cocktailView.ejs',
    'src/views/mixerView.ejs',
    'src/views/index.ejs',
    'app.js',
    'src/routes/alcoholRoutes.js',
    'src/routes/cocktailRoutes.js',
    'src/routes/mixerRoutes.js',
    'public/css/styles.css'
]
self.addEventListenent('install', function (e) {
    console.log('[Service Worker] Install')
    e.waitUntil(
        caches.open(cacheName).then(function (cache) {
            console.log('[Service Worker] Caching all: app shell and content')
            return cache.addAll(contentToCache)
        })
    )
})
self.addEventListener('fetch', function (e) {
    e.respondWith(
        caches.match(e.request).then(function (r) {
            console.log('[Service Worker] Caching new resource: '   e.request.url)
            return r || fetch(e.request).then(function (response){
                return caches.open(cacheName).then(function (cache) {
                    console.log('[Service Worker] caching new resource: '   e.request.url)
                    cache.put(e.request, response.clone())
                    return response
                })
            })
        })
    )
})

self.addEventListener('activate', (e) => {
    e.waitUntil(
        caches.keys().then((keyList)=>{
            return Promise.all(keyList.map((key)=>{
                if(cacheName.indexOf(key)===-1){
                    return caches.delete(key)
                }
            }))
        })
    )
})

Any advice into why it doesnt want to recognise this as a pwa would be greatly appreciated, thanks

CodePudding user response:

the first part of your code is running on server but service-worker runs on browsers in client side, so if('serviceWorker' in navigator) is always false , you should add if('serviceWorker' in navigator){ navigator.serviceWorker.register('sw.js') } in app.js file for client in /public directory

  • Related