其实很简单,照着我的步骤来,你也可以轻松部署!
首先你得有CF账户,只要邮箱就可以注册!
注册地址
注册成功并登陆。
第一步:创建 Worker 脚本
进入 Cloudflare Workers 控制台
点击左侧 “Workers & Pages” > “Workers”
点击右上角 “Create Worker”
在弹出的编辑器中,清空默认代码,粘贴以下内容:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| export default { async fetch(request, env, ctx) { const url = new URL(request.url); const path = url.searchParams.get("path") || "default";
let count = await env.VIEW_KV.get(path); count = count ? parseInt(count) : 0; count += 1; await env.VIEW_KV.put(path, count);
return new Response(JSON.stringify({ views: count }), { headers: { "Content-Type": "application/json", "Access-Control-Allow-Origin": "*" }, }); }, };
|
- 保存部署(Save and Deploy)
- 右上角点击绿色按钮。
第二步:添加 KV 存储
仍在该 Worker 页左侧,点击 “Settings” > “KV namespaces”
点击 “Add binding”
Variable name 填:VIEW_KV
Select a namespace:点击 “Create new namespace”
名字随便填,比如 hexo-view-counter,保存即可。
第三步:测试接口是否正常
在浏览器访问:
1
| https://<your-worker-subdomain>.workers.dev/?path=/hello
|
你会看到返回:
再次刷新:
第四步:在 Hexo 主题中添加阅读量显示
在 你的主题的 /layout/_partial/post/metadata.ejs 文件或页面底部模板中,添加:
1 2 3 4 5 6 7 8 9 10 11 12
| <span id="view-count">阅读量加载中...</span> <script> const path = window.location.pathname; fetch(`https://your-worker-subdomain.workers.dev?path=${encodeURIComponent(path)}`) .then(res => res.json()) .then(data => { document.getElementById('view-count').innerText = `阅读量:${data.views}`; }) .catch(() => { document.getElementById('view-count').innerText = '读取失败'; }); </script>
|
好了!一切大功告成!