在现代Web应用中,前后端的数据交互是实现动态功能的关键。本教程将指导您如何在前端页面上实现一个点赞按钮,该按钮默认显示点赞数,点击后点赞数加一,并调用后端的点赞API记录用户的点赞事件。

点赞功能需求分析

在实现点赞功能之前,我们需要明确功能需求:

  1. 显示当前点赞数:从后端API获取当前的点赞总数并显示
  2. 点赞按钮:提供一个按钮供用户点击表达赞意
  3. 增加点赞数:用户点击按钮后,点赞数应实时增加
  4. 防止重复点赞:同一个用户(通过IP识别)在一定时间内不能重复点赞
  5. 视觉反馈:用户操作后应有明确的视觉反馈

更新主页以添加点赞功能

我们需要修改主页文件,在页面中添加点赞按钮和计数器。

修改主页文件

打开public/index.html文件,更新内容以添加点赞功能:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>我的Express应用</title>
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="/css/bootstrap.min.css">
<!-- Bootstrap Icons -->
<link rel="stylesheet" href="/css/bootstrap-icons.css">
<!-- 自定义CSS -->
<style>
body {
padding-top: 20px;
}
.feature-icon {
width: 4rem;
height: 4rem;
border-radius: .75rem;
}
.clock-container {
text-align: center;
margin: 30px 0;
}
.digital-clock {
font-size: 3rem;
font-weight: bold;
font-family: 'Courier New', monospace;
color: #0d6efd;
background-color: #f8f9fa;
padding: 20px;
border-radius: 10px;
box-shadow: 0 4px 8px rgba(0,0,0,0.1);
}
.time-info {
margin-top: 10px;
font-size: 1.2rem;
}
/* 点赞按钮样式 */
.thumbsup-container {
text-align: center;
margin: 30px 0;
padding: 20px;
background-color: #f8f9fa;
border-radius: 10px;
}
.thumbsup-btn {
font-size: 1.5rem;
padding: 10px 20px;
border: 2px solid #0d6efd;
background-color: white;
color: #0d6efd;
border-radius: 50px;
cursor: pointer;
transition: all 0.3s ease;
}
.thumbsup-btn:hover {
background-color: #0d6efd;
color: white;
}
.thumbsup-btn:disabled {
background-color: #6c757d;
border-color: #6c757d;
color: white;
cursor: not-allowed;
}
.thumbsup-count {
font-size: 2rem;
font-weight: bold;
color: #0d6efd;
margin: 0 15px;
}
.thumbsup-icon {
color: #ffc107;
font-size: 1.8rem;
}
.feedback-message {
margin-top: 10px;
font-weight: bold;
}
.success {
color: #198754;
}
.error {
color: #dc3545;
}
.info {
color: #0d6efd;
}
</style>
</head>
<body>
<div class="container">
<header class="d-flex align-items-center pb-3 mb-5 border-bottom">
<h1 class="h2">欢迎来到我的Express应用</h1>
</header>

<!-- 实时时钟组件 -->
<div class="clock-container">
<h2>北京时间</h2>
<div id="digital-clock" class="digital-clock">
--:--:--
</div>
<div id="time-info" class="time-info">
正在获取时间数据...
</div>
<button id="refresh-btn" class="btn btn-primary mt-3">
<i class="bi bi-arrow-clockwise"></i> 刷新时间
</button>
</div>

<!-- 点赞组件 -->
<div class="thumbsup-container">
<h2>点赞支持</h2>
<div class="d-flex align-items-center justify-content-center">
<button id="thumbsup-btn" class="thumbsup-btn">
<i class="bi bi-hand-thumbs-up thumbsup-icon"></i> 点赞
</button>
<span id="thumbsup-count" class="thumbsup-count">0</span>
<div>
<span class="fs-5">个赞</span>
</div>
</div>
<div id="feedback-message" class="feedback-message"></div>
</div>

<div class="row g-4 py-5 row-cols-1 row-cols-lg-3">
<div class="col d-flex align-items-start">
<div class="icon-square text-body-emphasis bg-body-secondary d-inline-flex align-items-center justify-content-center fs-4 flex-shrink-0 me-3">
<i class="bi bi-bootstrap"></i>
</div>
<div>
<h3 class="fs-4">Bootstrap框架</h3>
<p>使用Bootstrap快速构建响应式网页,让网站在各种设备上都有良好的显示效果。</p>
<a href="#" class="btn btn-primary">
了解更多
</a>
</div>
</div>
<div class="col d-flex align-items-start">
<div class="icon-square text-body-emphasis bg-body-secondary d-inline-flex align-items-center justify-content-center fs-4 flex-shrink-0 me-3">
<i class="bi bi-file-code"></i>
</div>
<div>
<h3 class="fs-4">Express.js</h3>
<p>基于Node.js的快速、开放、极简的Web应用框架,为构建Web应用和API提供强大功能。</p>
<a href="#" class="btn btn-primary">
了解更多
</a>
</div>
</div>
<div class="col d-flex align-items-start">
<div class="icon-square text-body-emphasis bg-body-secondary d-inline-flex align-items-center justify-content-center fs-4 flex-shrink-0 me-3">
<i class="bi bi-lightning"></i>
</div>
<div>
<h3 class="fs-4">高性能</h3>
<p>采用事件驱动、非阻塞I/O模型,使其轻量又高效,能够处理大量并发请求。</p>
<a href="#" class="btn btn-primary">
了解更多
</a>
</div>
</div>
</div>

<footer class="pt-5 my-5 text-body-secondary border-top">
&copy; 2025 我的Express应用 - 使用Bootstrap v5构建
</footer>
</div>

<!-- Bootstrap JS -->
<script src="/js/bootstrap.bundle.min.js"></script>
<!-- 自定义JavaScript -->
<script>
// 获取北京时间的函数
async function getBeijingTime() {
try {
// 显示加载状态
document.getElementById('digital-clock').textContent = '--:--:--';
document.getElementById('time-info').textContent = '正在获取时间数据...';

// 调用API获取北京时间
const response = await fetch('/api/beijing-time');

// 检查响应状态
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}

// 解析JSON数据
const timeData = await response.json();

// 更新页面显示
updateClockDisplay(timeData);

return timeData;
} catch (error) {
console.error('获取时间失败:', error);
document.getElementById('time-info').textContent = '获取时间失败,请稍后重试';
}
}

// 更新时钟显示的函数
function updateClockDisplay(timeData) {
// 更新数字时钟显示
const timeParts = timeData.formattedTime.split(' ')[1].split(':');
document.getElementById('digital-clock').textContent =
`${timeParts[0]}:${timeParts[1]}:${timeParts[2]}`;

// 更新时间信息显示
document.getElementById('time-info').innerHTML = `
<strong>完整时间:</strong> ${timeData.formattedTime}<br>
<strong>时区:</strong> ${timeData.timezone} (UTC${timeData.utcOffset})<br>
<strong>ISO格式:</strong> ${timeData.currentTime}
`;
}

// 获取当前点赞数
async function getThumbsupCount() {
try {
const response = await fetch('/api/thumbsup-count');

if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}

const data = await response.json();
document.getElementById('thumbsup-count').textContent = data.count;

return data.count;
} catch (error) {
console.error('获取点赞数失败:', error);
showFeedback('获取点赞数失败', 'error');
}
}

// 点赞函数
async function thumbsup() {
try {
// 禁用按钮防止重复点击
const thumbsupBtn = document.getElementById('thumbsup-btn');
thumbsupBtn.disabled = true;

const response = await fetch('/api/thumbsup', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
}
});

if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}

const data = await response.json();

// 更新点赞数
const currentCount = parseInt(document.getElementById('thumbsup-count').textContent);
document.getElementById('thumbsup-count').textContent = currentCount + 1;

// 显示成功消息
showFeedback('谢谢您的点赞!', 'success');

// 3秒后恢复按钮状态
setTimeout(() => {
thumbsupBtn.disabled = false;
}, 3000);

return data;
} catch (error) {
console.error('点赞失败:', error);
showFeedback('点赞失败,请稍后重试', 'error');

// 恢复按钮状态
document.getElementById('thumbsup-btn').disabled = false;
}
}

// 显示反馈消息
function showFeedback(message, type) {
const feedbackElement = document.getElementById('feedback-message');
feedbackElement.textContent = message;
feedbackElement.className = `feedback-message ${type}`;

// 3秒后清除消息
setTimeout(() => {
feedbackElement.textContent = '';
feedbackElement.className = 'feedback-message';
}, 3000);
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
// 首次获取时间
getBeijingTime();

// 设置定时器,每秒更新一次时间显示
setInterval(function() {
getBeijingTime();
}, 1000);

// 首次获取点赞数
getThumbsupCount();

// 为刷新按钮添加点击事件
document.getElementById('refresh-btn').addEventListener('click', function() {
getBeijingTime();
});

// 为点赞按钮添加点击事件
document.getElementById('thumbsup-btn').addEventListener('click', function() {
thumbsup();
});
});
</script>
</body>
</html>

代码详细说明

HTML结构

  1. 点赞容器:创建了一个专门用于显示点赞功能的区域
  2. 点赞按钮:使用Bootstrap Icons的拇指向上图标
  3. 点赞计数器:显示当前点赞总数
  4. 反馈消息区域:显示操作结果的提示信息

CSS样式

  1. 点赞按钮样式

    • 使用边框和背景色区分默认和悬停状态
    • 添加过渡动画提升用户体验
    • 禁用状态样式防止重复点击
  2. 点赞计数器样式

    • 大字体显示点赞数
    • 使用醒目的颜色吸引注意
  3. 反馈消息样式

    • 不同类型消息使用不同颜色
    • 成功消息用绿色,错误消息用红色

JavaScript功能

  1. getThumbsupCount()函数

    • 调用/api/thumbsup-count API获取点赞总数
    • 更新页面上的点赞计数器
  2. thumbsup()函数

    • 调用/api/thumbsup API记录点赞事件
    • 禁用按钮防止重复点击
    • 更新点赞计数器
    • 显示操作结果反馈
  3. showFeedback()函数

    • 显示操作结果消息
    • 自动清除消息避免干扰

点赞功能工作原理

获取点赞数

前端通过Fetch API调用后端的/api/thumbsup-count端点获取点赞总数:

1
const response = await fetch('/api/thumbsup-count');

API返回的数据格式:

1
2
3
4
{
"count": 42,
"since": "2025-10-30T02:00:00.000Z"
}

点赞操作

用户点击点赞按钮时,前端发送POST请求到/api/thumbsup端点:

1
2
3
4
5
6
const response = await fetch('/api/thumbsup', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
}
});

防重复点赞机制

通过以下方式防止用户重复点赞:

  1. 按钮禁用:点击后立即禁用按钮
  2. 延时恢复:3秒后重新启用按钮
  3. 后端控制:后端通过IP地址识别用户并限制重复点赞

增强点赞功能

添加点赞历史显示

可以在页面中添加用户的点赞历史:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// 获取当前用户的点赞历史
async function getUserThumbsupHistory() {
try {
// 这里需要获取客户端IP,可以通过后端API获取
const response = await fetch('/api/thumbsup/user-history');

if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}

const data = await response.json();
// 更新页面显示用户点赞历史
updateThumbsupHistoryDisplay(data.records);
} catch (error) {
console.error('获取点赞历史失败:', error);
}
}

添加动画效果

为点赞操作添加动画效果:

1
2
3
4
5
6
7
8
9
.thumbsup-btn.clicked {
animation: pulse 0.5s;
}

@keyframes pulse {
0% { transform: scale(1); }
50% { transform: scale(1.1); }
100% { transform: scale(1); }
}
1
2
3
4
5
// 在点赞函数中添加动画
document.getElementById('thumbsup-btn').classList.add('clicked');
setTimeout(() => {
document.getElementById('thumbsup-btn').classList.remove('clicked');
}, 500);

前端与数据库交互最佳实践

1. 错误处理

始终处理网络错误和HTTP错误状态:

1
2
3
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}

2. 用户体验优化

  • 提供加载状态反馈
  • 防止重复操作
  • 给出明确的操作结果提示

3. 数据同步

  • 定期同步数据保持一致性
  • 处理并发更新冲突

4. 安全性考虑

  • 验证用户输入
  • 防止跨站请求伪造(CSRF)
  • 限制请求频率防止滥用

测试点赞功能

启动服务器

确保Express服务器正在运行:

1
npm start

访问主页

在浏览器中访问http://localhost:3000,您应该能看到:

  1. 页面中显示点赞按钮和计数器
  2. 点赞数从后端API获取并显示
  3. 点击按钮后计数器增加
  4. 操作结果有明确的视觉反馈

验证API调用

打开浏览器的开发者工具(F12),切换到Network标签页,可以观察到:

  1. 页面加载时向/api/thumbsup-count发送请求获取点赞数
  2. 点击点赞按钮时向/api/thumbsup发送POST请求
  3. HTTP状态码正确返回

总结

通过本教程,我们学习了如何:

  1. 在前端页面中添加点赞按钮和计数器
  2. 使用Fetch API与后端数据库进行交互
  3. 实现点赞数的获取和更新功能
  4. 添加防重复点击和用户反馈机制
  5. 应用前端与数据库交互的最佳实践

这些技能为构建具有用户交互功能的Web应用奠定了基础,使您的应用能够记录和展示用户的点赞行为。

参考文献

[1] MDN Web Docs, “Fetch API,” Mozilla Developer Network, 2023. [Online]. Available: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API. [Accessed: Oct. 30, 2025].


© 2025 MikeWu597 使用 Stellar 创建

琼ICP备2023004663号-3
湘公网安备 43010302001556号