Service Worker 未使用 nodejs 服务器在离线模式下运行 [英] Service worker not run in offline mode using nodejs server

查看:53
本文介绍了Service Worker 未使用 nodejs 服务器在离线模式下运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在创建新项目 PWA.当我开发时不使用节点 js(socket.io 运行)只是像我预期和需要的那样离线运行.

i've been create new project PWA. when i develop not using node js for (socket.io running) just running in offline like i expected and needed.

但是当与 nodejs 服务器集成时.上网时,应用程序运行良好不会出现任何问题.但是当我切换到离线模式时,我的服务没有运行,而是显示离线浏览器.

but when integration with nodejs server. when go online the app running well not get any problem. but when i change to offline mode my service work not run but show offline browser.

这是我的代码节点js服务器:

this my code node js server:

var express = require('express');
var app = express();
var server = require('http').Server(app);
var io = require('socket.io')(server);
var cors = require('cors');

app.use(cors());
app.use(express.static(__dirname + '/'));

app.use(function(req, res, next){
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
  res.header('Access-Control-Allow-Headers', 'Content-Type');
  next();
});


io.on('connection', function(socket) {
  console.log('new connection');

  socket.on('afterBid', function(data) {
    io.emit('bcCurrentBid', {
      current_bidding: data.auction_current_bidding,
      user_id_dominated: data.user_id_dominated
    });
  });

});

server.listen(9991, function() {
  console.log('server up and running at 2205 port');
});

这是我在 index js 中的服务注册

and this is my service register in index js

if ('serviceWorker' in navigator && 'PushManager' in window) {
		console.log('Service Worker and Push is supported');

	  window.addEventListener('load', function() {
			navigator.serviceWorker
             .register('./service-worker.js')
             .then(function() { console.log('Service Worker Registered'); });
	  });
	}

这是我的 service-worker.js 文件:

and this is my service-worker.js file:

var cacheName = 'Auction-v2';
var filesToCache = [
  'index.html',
  'server.js',
  '/',
  './app/app.js',
  './app/listAuctionController.js',
  './app/auctionDetailController.js',
  './app/service/auctionDataService.js',
  './media/frontend/images/auction_logo_white.png',
  // './media/frontend/',
  // './media/catalog/',
  // './view/',
  './lib/css/materialize.min.css',
  './lib/css/owl.carousel.min.css',
  './lib/css/jquery.countdown.css',
  './lib/css/owl.theme.default.min.css',
  './lib/css/materialize-icon.css',
  './lib/js/jquery.min.js',
  './lib/js/jquery.lazyLoad.js',
  './lib/js/jquery.maskMoney.js',
  './lib/js/jquery.countdown.min.js',
  './lib/js/materialize.min.js',
  './lib/js/owl.carousel.min.js',
  './lib/js/angular/angular.min.js',
  './lib/js/angular/angular-route.min.js',
  './lib/js/angular/angular-sanitize.min.js',
  './lib/js/angular/angular-locale_id-id.js',
  './lib/js/angular/angular-animate.min.js',
];

var dataCacheName = 'Auction-Data-v1';

// SW Install
self.addEventListener('install', function(e) {
  console.log('[ServiceWorker] Install');
  e.waitUntil(
    caches.open(cacheName).then(function(cache) {
      console.log('[ServiceWorker] Caching app shell');
      return cache.addAll(filesToCache);
    })
  );
});




self.addEventListener('fetch', function(e) {
  // console.log('[Service Worker] Fetch', e.request.url);
  var dataUrl = '/backendFrame/public/api/v1/';
  var dataUrl2 = '/view/';
  if (e.request.url.indexOf(dataUrl) > -1 || e.request.url.indexOf(dataUrl2)) {
    /*
     * When the request URL contains dataUrl, the app is asking for fresh
     * weather data. In this case, the service worker always goes to the
     * network and then caches the response. This is called the "Cache then
     * network" strategy:
     * https://jakearchibald.com/2014/offline-cookbook/#cache-then-network
     */
    e.respondWith(
      caches.open(dataCacheName).then(function(cache) {
        return fetch(e.request).then(function(response){
          // console.log('url to cache =' + e.request.url);
          cache.put(e.request.url, response.clone());
          return response;
        });
      })
    );
  } else {
    /*
     * The app is asking for app shell files. In this scenario the app uses the
     * "Cache, falling back to the network" offline strategy:
     * https://jakearchibald.com/2014/offline-cookbook/#cache-falling-back-to-network
     */
    e.respondWith(
      caches.match(e.request).then(function(response) {
        return response || fetch(e.request);
      })
    );
  }
});

// SW Activate
self.addEventListener('activate', function(e) {
  console.log('[ServiceWorker] Activate');
  e.waitUntil(
    caches.keys().then(function(keyList) {
      return Promise.all(keyList.map(function(key) {
        if (key !== cacheName  && key !== dataCacheName) {
          console.log('[ServiceWorker] Removing old cache', key);
          return caches.delete(key);
        }
      }));
    })
  );
  return self.clients.claim();
});

谢谢,也许有人可以给我解决方案

thanks maybe someone can give me solution

推荐答案

我在这里发布了一个类似的问题并得到了答案:Service Worker 不使用节点在离线模式下工作js服务器

I posted a similar question here and got an answer : Service Worker not working in Offline mode with node js server

简而言之,请记住 service worker 的作用域是它自己的目录 和下面的文件夹...并且它无法访问您的 lib 或应用程序目录...

To make it short, keep in mind the service worker's scope is its own directory and folders below... and it cannot access your lib or app directories...

更详细地说,这意味着如果您的内容从 https://example.com/ 开始,则您的 Service Worker 必须位于 https://example.com/service-worker.js.如果你把它写成 https://example.com/js/service-worker.js,它就不会正常工作.

In more detail, this means that if your content starts at https://example.com/, your service worker must live at https://example.com/service-worker.js. It won't function right if you put it as https://example.com/js/service-worker.js.

这篇关于Service Worker 未使用 nodejs 服务器在离线模式下运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆