首页 > 解决方案 > 使用响应类型“cors”在缓存中创建响应

问题描述

我在更新缓存存储中的缓存以在应用程序离线时反映我们的更改时遇到问题,因为我无法创建具有“cors”类型的响应对象,该对象是应用程序在线时缓存的对象。

我需要用 a 更新以前的缓存响应,因为应用程序在离线Response-Type: cors时尝试再次获取请求时会查找具有相似属性的请求-响应对。GET

我尝试使用cache.put(req, res). 但是,我不能在程序上创建一个响应类型为“cors”的响应对象,因为它只创建“默认”,除非通过它似乎产生的实际网络调用。

Response-Type: cors有什么方法可以使用或更新现有的缓存主体来制作 Response 对象?

我尝试对extendsResponse 对象启用修改Response-Type

这是更新缓存的代码:

// Extend Response to use Response-Type cors
class CacheResponse extends Response {
    type = "cors";
    url = "https://localhost:5001/api/Customer?id=e2b9b098-2fd8-423b-8928-e234d80d39ed";
}

// PUT the cache
caches.open("ngsw:1:data:dynamic:api-customer:cache").then((cache) => {

    let req = new Request("https://localhost:5001/api/Customer?id=e2b9b098-2fd8-423b-8928-e234d80d39ed", {
        method: "GET",
        mode: undefined,
        headers: {
            'Accept': "application/json",
            'User-Agent': "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36",
            'Origin': 'https://localhost:9001',
            'Referer': 'https://localhost:9001/app/customers/e2b9b098-2fd8-423b-8928-e234d80d39ed'
        }
    })

    let res = new CacheResponse(
        JSON.stringify({
            "id": "e2b9b098-2fd8-423b-8928-e234d80d39ed",
            "name": "Alvin Long",
        }), {
            headers: {
                'Content-Type': 'application/json; charset=utf-8',
                'Access-Control-Allow-Origin': '*',
                'Date': 'Fri, 05 Jul 2019 14:47:27 GMT',
                'Server': 'Kestrel',
                'Transfer-Encoding': 'chunked',
            },
            type: "cors"
        });

    cache.put(req, res)
});

这将创建另一个缓存,除了Response-Type

标签: javascriptcorsservice-workerprogressive-web-appscachestorage

解决方案


推荐阅读