KV 是什么?免费吗? Cloudflare KV 是官方自带的轻量键值数据库,完全免费(免费额度:每天 10 万次读取、1000 次写入、1GB 容量,个人使用永远不会超标)。
启用跨设备同步只需 2 步:
① 将本网页保存为 index.html,并在同目录新建文件夹与文件 functions/api/ent.js(内容如下);
② 在 Cloudflare Pages 后台绑定 KV 命名空间(变量名填 ENT_KV),并添加环境变量 ACCESS_PASSWORD 作为你的密码即可!
export async function onRequest(context) {
const { request, env } = context;
const pwd = request.headers.get("X-Auth-Password") || "";
const expected = env.ACCESS_PASSWORD || "1234";
if (pwd !== expected) {
return new Response(JSON.stringify({ error: "UNAUTHORIZED" }), {
status: 401,
headers: { "Content-Type": "application/json" }
});
}
if (request.method === "GET") {
const data = env.ENT_KV ? await env.ENT_KV.get("ENT_DATA") : null;
return new Response(data || "null", {
headers: { "Content-Type": "application/json" }
});
}
if (request.method === "POST") {
const body = await request.text();
if (env.ENT_KV) {
await env.ENT_KV.put("ENT_DATA", body);
}
return new Response(JSON.stringify({ ok: true }), {
headers: { "Content-Type": "application/json" }
});
}
return new Response("Method Not Allowed", { status: 405 });
}