我想为我的 Tumblr 博客创建一个点击计数器。但由于我使用的是 localStorage,因此无法显示所有客户端号码。我应该用什么来代替它?谢谢你!
代码
var visitCount = localStorage.getItem("page_view");
if (visitCount) {
visitCount = Number(visitCount) + 1;
localStorage.setItem("page_view", visitCount);
} else {
visitCount = 1;
localStorage.setItem("page_view", 1);
}
counterContainer.innerHTML = visitCount;
如果我理解正确的话...
您在使用
localStorage
的点击计数器时遇到的问题可能是由于 localStorage
仅在客户端存储数据,并且它特定于每个客户端的浏览器。
这意味着,如果用户从不同的设备或浏览器访问您的 Tumblr 博客,点击计数器将不会显示统一的计数。 以下是如何实现这一目标的基本概述:
来实现 服务器端 代码的高级示例:
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
// Connect to your database
mongoose.connect('mongodb://localhost/hitcounterdb');
// Create a schema and model for hit counts
const hitCountSchema = new mongoose.Schema({
count: Number,
});
const HitCount = mongoose.model('HitCount', hitCountSchema);
app.use(bodyParser.json());
// Endpoint to get the hit count
app.get('/api/hitcount', async (req, res) => {
try {
const hitCount = await HitCount.findOne();
if (!hitCount) {
res.json({ count: 0 });
} else {
res.json({ count: hitCount.count });
}
} catch (error) {
console.error(error);
res.status(500).json({ error: 'Internal Server Error' });
}
});
// Increment the hit count
app.post('/api/increment', async (req, res) => {
try {
let hitCount = await HitCount.findOne();
if (!hitCount) {
hitCount = new HitCount({ count: 1 });
} else {
hitCount.count++;
}
await hitCount.save();
res.json({ count: hitCount.count });
} catch (error) {
console.error(error);
res.status(500).json({ error: 'Internal Server Error' });
}
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});