使用缓存存储API保存自定义响应 [英] Saving a custom Response using the Cache Storage API

查看:71
本文介绍了使用缓存存储API保存自定义响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用缓存存储来构建渐进式Web应用程序(PWA)。我需要输入有一个自定义对象进入我的缓存,但是缓存将响应对象作为论据。所以我的问题是如何正确创建其中包含JSON的Response对象。我知道我可以使用其他缓存策略(localStorage或IndexedDB),但我对此情况特别好奇-将自定义JSON作为请求保存在缓存中。

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


推荐答案

可以;如果您的网络应用有意义,则可以这样做。您可以在支持Cache Storage API的任何地方(例如,在服务工作者中或在受控页面的上下文中)进行操作。这是一个基本示例:

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));

您可以通过记录类似

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

这篇关于使用缓存存储API保存自定义响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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