如何将 PWA 功能添加到 Express Web 应用程序

How to add PWA functionality to a express web app

我目前正在尝试将 PWA 集成添加到 Web 应用程序。我创建了一个 manifest.json 并将其添加到我的页面的头部,加载正常,但是在我的 app.js 中注册的 serviceworker 似乎没有做任何事情。

下面是我用来设置应用程序的代码部分:

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')
}

这是我的 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)
                }
            }))
        })
    )
})

任何关于为什么它不想将其识别为 pwa 的建议将不胜感激,谢谢

你的代码的第一部分是 运行 在服务器上,但是 service-worker 在客户端的浏览器上运行,所以 if('serviceWorker' in navigator) 总是 false ,你应该在 app.js /public 目录中的客户端文件