Saving a custom Response using the Cache Storage API

半世苍凉 提交于 2019-12-09 23:57:49

问题


I'm using Cache Storage to build an progressive web app ( PWA ). There is a custom object that I need to put into my cache, but the cache accepts Response objects as an argument. So my question is how to properly create Response object, that has the JSON in it. I know I can use other caching strategies ( localStorage or IndexedDB ) but I'm particularly curious about this case - saving custom JSON in cache as a request.

var myJSON = JSON.stringify({custom:"object"}); 
caches.open('cache-name').then(function (cache) {
  var response = new Response(); //My JSON should go into this Response obj. 
  return cache.put('cache-name', response);
});

回答1:


Sure; it's possible to do that if it makes sense for your web app. You can do it wherever the Cache Storage API is supported, i.e. either in a service worker or from the context of a controlled page. Here's a basic example:

const data = {
  1: 2,
  3: 4
};

const jsonResponse = new Response(JSON.stringify(data), {
  headers: {
    'content-type': 'application/json'
  }
});

caches.open('json-cache').then(cache => cache.put('/data.json', jsonResponse));

You can manually confirm that the data you expect is being stored via logging something like

caches.match('/data.json').then(r => r.json()).then(console.log)


来源:https://stackoverflow.com/questions/40619272/saving-a-custom-response-using-the-cache-storage-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!