Cloudflare定时Worker将API响应存入KV失败问题求助
问题:Cloudflare定时Worker无法将access_token存入KV存储
我之前通过CRON触发成功存储过KV,现在想通过Cloudflare定时(CRON)Worker把API响应里的access_token存入KV,供后续前端调用。我写了如下代码,但两种存储尝试都没成功,KV里没有保存数据:
addEventListener("scheduled", (event) => { console.log("cron trigger processed..", event); event.waitUntil(handleRequest()); }); async function handleRequest() { const url = "<request_url>"; const body = { <credential> }; const init = { body: JSON.stringify(body), method: "POST", headers: { "content-type": "application/json;charset=UTF-8" } }; const response = await fetch(url, init); const results = await gatherResponse(response); //@ts-ignore AUTH.put("attempt1", results); //@ts-ignore AUTH.put("attempt2", new Response(results, init)); return new Response(results, init); } /** * gatherResponse awaits and returns a response body as a string. * Use await gatherResponse(..) in an async function to get the response body * @param {Response} response */ async function gatherResponse(response) { const { headers } = response const contentType = headers.get("content-type") || "" if (contentType.includes("application/json")) { return JSON.stringify(await response.json()) } else if (contentType.includes("application/text")) { return await response.text() } else if (contentType.includes("text/html")) { return await response.text() } else { return await response.text() } }
其中这两行存储操作均未生效:
//@ts-ignore AUTH.put("attempt1", results); //@ts-ignore AUTH.put("attempt2", new Response(results, init));
解决方案
核心问题:未等待KV异步操作完成
AUTH.put()是异步函数,当前代码直接调用但未用await等待执行完成,Worker事件循环可能在KV操作结束前就终止,导致存储失败。
具体修复:
- 给KV存储操作添加
await,确保操作完成后再结束函数:
//@ts-ignore await AUTH.put("attempt1", results); //@ts-ignore await AUTH.put("attempt2", results); // 去掉不必要的Response包装
- 优化存储逻辑(可选):如果只需要
access_token,建议解析响应后直接存储目标字段,减少冗余:
// 替换原来的gatherResponse调用,直接解析JSON const responseData = await response.json(); // 只存储需要的access_token await AUTH.put("access_token", responseData.access_token);
- 确认Worker已正确绑定
AUTH命名空间:在Cloudflare控制台的Worker设置中,检查KV命名空间的绑定名称是否为AUTH,名称不匹配会导致存储无响应。
内容的提问来源于stack exchange,提问作者Shinjo
相关产品推荐
相关产品推荐

