如何正确配置Cloudflare Worker将提交对象存储到Cloudflare KV?
问题排查及修复方案
核心错误点
- 函数名拼写错误:Worker中你定义的KV写入函数是
setCache,但实际调用时写的是setData,未定义的函数调用直接触发500错误,这是你请求报错的直接原因 - 逻辑错误:当前代码是直接用新提交的单条文章覆盖KV中的
posts值,没有做数组追加操作,就算修复函数名也只会存储最新提交的单条文章,不会形成数组 - 缺少CORS预检请求处理:跨域POST请求会先发送OPTIONS预检请求,未处理的话会导致前端跨域报错
修复后的Worker代码
// 需提前在Worker配置面板绑定KV命名空间,绑定的变量名和代码中的name_data保持一致 const setCache = (key, data) => name_data.put(key, data) const getCache = key => name_data.get(key) async function handleRequest(request) { const headers = { 'Allow': 'OPTIONS, GET, HEAD, POST', 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods': 'OPTIONS, GET, POST', 'Access-Control-Allow-Headers': 'Content-Type', 'Content-type': 'application/json', } // 处理预检请求 if (request.method === 'OPTIONS') { return new Response(null, { status: 204, headers }) } if (request.method !== 'POST') { return new Response(JSON.stringify({msg: '仅支持POST请求'}), { status: 405, headers }) } try { const body = await request.text() const newPost = JSON.parse(body) const dataKey = `posts` // 读取现有posts数组 const existPosts = await getCache(dataKey) let postsArr = [] if (existPosts) { postsArr = JSON.parse(existPosts) } // 追加新文章 postsArr.push(newPost) // 序列化后写入KV await setCache(dataKey, JSON.stringify(postsArr)) return new Response(JSON.stringify({code: 0, msg: '保存成功', data: newPost}), { status: 200, headers }) } catch (err) { return new Response(JSON.stringify({code: 1, msg: err.message}), { status: 500, headers }) } } export default handleRequest
前端代码可选优化
把注释掉的Content-Type配置打开,更符合HTTP规范:
const onSavePostClicked = async () => { if (canSave) { const data = { title, content, author, id: nanoid() }; fetch('https://serverless-api.mySpace.workers.dev/api/add', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(data), }) .then((response) => response.json()) .then((res) => { console.log('Success:', res); setTitle(''); setContent(''); setAuthor(''); }) .catch((error) => { console.error('Error:', error); }); } };
额外注意事项
- 确认Worker配置中已正确绑定KV命名空间,绑定的变量名和代码中使用的
name_data完全一致 - KV写入有最高1秒的一致性延迟,写入后立即读取可能拿到旧数据,属于正常特性
内容的提问来源于stack exchange,提问作者captaincustard
相关产品推荐
相关产品推荐

