// Cloudflare Worker - 备忘录 API // KV 绑定变量名:remind export default { async fetch(request, env) { const url = new URL(request.url); const path = url.pathname; // 跨域头(允许网页调用) const corsHeaders = { 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods': 'GET, POST, DELETE, OPTIONS', 'Access-Control-Allow-Headers': 'Content-Type', }; if (request.method === 'OPTIONS') { return new Response(null, { headers: corsHeaders }); } // 仅处理 /api/memos if (path !== '/api/memos') { return new Response('Not Found', { status: 404, headers: corsHeaders }); } // 获取当前储存的备忘录数组 async function getMemos() { const data = await env.remind.get('memos'); return data ? JSON.parse(data) : []; } // 保存数组到 KV async function saveMemos(memos) { await env.remind.put('memos', JSON.stringify(memos)); } // ----- GET:获取所有备忘录 ----- if (request.method === 'GET') { const memos = await getMemos(); return new Response(JSON.stringify(memos), { headers: { 'Content-Type': 'application/json', ...corsHeaders }, }); } // ----- POST:添加一条备忘录 ----- if (request.method === 'POST') { const body = await request.json(); const { text } = body; if (!text || typeof text !== 'string') { return new Response(JSON.stringify({ error: '缺少 text 字段' }), { status: 400, headers: { 'Content-Type': 'application/json', ...corsHeaders }, }); } const memos = await getMemos(); memos.push({ text, time: Date.now() }); // 带时间戳方便识别 await saveMemos(memos); return new Response(JSON.stringify(memos), { headers: { 'Content-Type': 'application/json', ...corsHeaders }, }); } // ----- DELETE:根据 index 删除一条 ----- if (request.method === 'DELETE') { const index = parseInt(url.searchParams.get('index'), 10); if (isNaN(index)) { return new Response(JSON.stringify({ error: '需要 index 参数' }), { status: 400, headers: { 'Content-Type': 'application/json', ...corsHeaders }, }); } const memos = await getMemos(); if (index < 0 || index >= memos.length) { return new Response(JSON.stringify({ error: '索引超出范围' }), { status: 400, headers: { 'Content-Type': 'application/json', ...corsHeaders }, }); } memos.splice(index, 1); await saveMemos(memos); return new Response(JSON.stringify(memos), { headers: { 'Content-Type': 'application/json', ...corsHeaders }, }); } return new Response('Method Not Allowed', { status: 405, headers: corsHeaders }); }, };