码迷,mamicode.com
首页 > 其他好文 > 详细

[PWA] Show an Error when a POST or DELETE Fails in an Offline PWA

时间:2018-12-30 15:11:55      阅读:220      评论:0      收藏:0      [点我收藏+]

标签:hand   listen   str   fir   string   caching   class   client   when   

We‘re storing JSON data in the cache - but that only applies to HTTP GET requests - and not to POST or DELETE requests.

We‘ll add a fetch event listener to the service worker, where we can intercept all fetch requests in our app. We‘ll forward them to the server - but if they fail, then we‘ll return an error back to the app.

In the app, we can detect that error, and respond by showing an alert that the functionality isn‘t available in offline mode.

 

console.log("IN sw.js")

workbox.skipWaiting();
workbox.clientsClaim();

workbox.routing.registerRoute(
    new RegExp(‘https:.*min\.(css|js)‘),
    workbox.strategies.staleWhileRevalidate({
        cacheName: ‘cdn-cache‘
    })
  )

  workbox.routing.registerRoute(
    new RegExp(‘(http|https|localhost)://.*:4567.*\.json‘),
    workbox.strategies.networkFirst()
  )

 // Handle the POST and DELETE requests by SW
  self.addEventListener(‘fetch‘, event => {
    if (event.request.method === "POST" || event.request.method === "DELETE") {
      event.respondWith (
        fetch(event.request).catch(err => {
          return new Response(
            JSON.stringify({error: "This action disabled while app is offline"}),
            {headers: {
              ‘Content-Type‘: ‘application/json‘
            }}
          )
        })
      )
    }
  })

workbox.precaching.precacheAndRoute(self.__precacheManifest || [])

 

[PWA] Show an Error when a POST or DELETE Fails in an Offline PWA

标签:hand   listen   str   fir   string   caching   class   client   when   

原文地址:https://www.cnblogs.com/Answer1215/p/10199432.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!