NodeJS 用Javascript访问Cache上的body响应

0h4hbjxa  于 2023-06-05  发布在  Node.js
关注(0)|答案(2)|浏览(228)

我正在使用node.js,我想在缓存中存储一些数据。
请求已成功存储。

const version = "3.4.3";
caches.open('v' + version)
.then(async cache => {
    await cache.add('/getTranslations');
    const data = await cache.match('/getTranslations');
});

下面是endpoint返回的内容:

app.get("/getTranslations", (req, res) => {
            res.status(200).send(/*Here is the object shown 
            on the next picture and what i want to read from cache*/);
});

我在chrome的cache上有这个:

我试图访问什么是显示在预览,但我无法得到它。
使用

// In my case the name of the cache is 'v4'
const c = await caches.open('v4');

// Here finds the 7 requests.
await c.keys()

// Here i get the request but i can't not get the data I'm looking for.
await c.match('/getTranslations')
mrwjdhj3

mrwjdhj31#

在这里,我自己用JavaScript找到了解决方案:例如,问题请求上显示的内容将是'/getTranslations',版本将是'4'。

cachePetition: async function (version: string, request: string) {
        let body = -1;
        return caches.open('v' + version).then(async cache => {
            // Function to get the cached data
            const writeRequestToCache = async () => {
                console.log("[Cache] Getting '" + request + "' ...");
                await cache.add(request);
                const result = await cache.match(request);
                return result.json();
            }

            let data = await cache.match(request);

            // If there is no data in the cache, get it from the server
            if (data == undefined) {
                console.log("[Cache] '" + request + "' not found.");
                body = await writeRequestToCache();
            } else {
                body = await data.json();
                // If you can't access to the body of the petition ask it again. This is a workaround for the cache bug.
                if (body == undefined) {
                    console.log("[Cache] '" + request + "' data corrupted. Getting it again...");
                    body = await writeRequestToCache();
                } else {
                    console.log("[Cache] '" + request + "' found.");
                }
            }
            return body;
        });
    }
44u64gxh

44u64gxh2#

如果你只想从该高速缓存中获取数据,只需使用一个简单的函数,就可以了:

async function getCachedData(storageName, path) {
  return await caches
    .open(storageName)
    .then((cache) => cache.match(path))
    .then((data) => data?.json());
}

在您的情况下,调用应该是:

getCachedData('v4', '/getTranslations')

相关问题