Cloudflare worker Cache not work
Hi, I tried to put the cache but not work, not sure why.
here is my code
app.get('/get_all_order_status', async (ctx) => {
const cacheUrl = ctx.req.url;
const cacheKey = new Request(cacheUrl.toString(), ctx.req);
const cache = caches.default;
let fromCache = true; let response = await cache.match(cacheKey); if (!response) { const data = await Model.getAllOrderStatus(); response = new Response(JSON.stringify(data), { headers: { 'content-type': 'application/json' }, }); // Add a custom header to the response before putting it in the cache fromCache = false; // Cache the response indefinitely try { console.log(cacheKey.method, cacheKey.url); console.log(response.status, response.statusText); response.headers.append("Cache-Control", "s-maxage=10000000"); ctx.executionCtx.waitUntil(cache.put(cacheKey, response.clone())); } catch (error) { console.error('Error putting data in cache:', error); } } response.headers.set('X-From-Cache', fromCache.toString()); return response; }); The cacheKey and response is OK but cache.put not work.
let fromCache = true; let response = await cache.match(cacheKey); if (!response) { const data = await Model.getAllOrderStatus(); response = new Response(JSON.stringify(data), { headers: { 'content-type': 'application/json' }, }); // Add a custom header to the response before putting it in the cache fromCache = false; // Cache the response indefinitely try { console.log(cacheKey.method, cacheKey.url); console.log(response.status, response.statusText); response.headers.append("Cache-Control", "s-maxage=10000000"); ctx.executionCtx.waitUntil(cache.put(cacheKey, response.clone())); } catch (error) { console.error('Error putting data in cache:', error); } } response.headers.set('X-From-Cache', fromCache.toString()); return response; }); The cacheKey and response is OK but cache.put not work.
2 Replies
Are you seeing an error when adding an item to cache or what does not work mean?
I am not sure, the
let response = await cache.match(cacheKey);
always return null.
so I guest the ctx.executionCtx.waitUntil(cache.put(cacheKey, response.clone())); not working. But it not go to the catch error, just no err show
I put the X-From-Cache - If it hit cache it will be true, but always false.
the response always null, so the code always go to Model - hit database and get data, not from cache
hi any advise?
oh found the issue, Cache API is not enabled on workers.dev