设计一个接口统计当天该按钮的点击次数,只要是在这一天时间范围内点击就给,数量加一(给出node示例代码)
时间: 2023-11-27 11:54:24 浏览: 34
以下是一个简单的Node.js代码示例,实现了一个统计当天按钮点击次数的接口:
```javascript
const express = require('express');
const app = express();
const port = 3000;
// 存储点击次数的对象,以日期为键
const clickCount = {};
// 格式化日期函数,返回格式为 'YYYY-MM-DD' 的日期字符串
function formatDate(date) {
const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, '0');
const day = String(date.getDate()).padStart(2, '0');
return `${year}-${month}-${day}`;
}
// 点击次数统计中间件
function countClicks(req, res, next) {
const dateStr = formatDate(new Date());
if (!clickCount[dateStr]) {
clickCount[dateStr] = 0;
}
clickCount[dateStr]++;
next();
}
// 点击次数查询接口
app.get('/clicks', (req, res) => {
const dateStr = formatDate(new Date());
const count = clickCount[dateStr] || 0;
res.send(`Today's button clicks: ${count}`);
});
// 按钮点击接口,使用 countClicks 中间件统计点击次数
app.get('/button', countClicks, (req, res) => {
res.send('Button clicked');
});
app.listen(port, () => {
console.log(`Listening on port ${port}`);
});
```
使用方法:
1. 在终端中进入代码所在的目录,运行 `npm install express` 安装依赖。
2. 运行 `node app.js` 启动应用。
3. 访问 `http://localhost:3000/button`,可以看到输出 `Button clicked`。
4. 访问 `http://localhost:3000/clicks`,可以看到输出类似于 `Today's button clicks: 1` 的内容。每次访问 `/button` 接口都会使点击次数加一,因此这里的数字会不断增加。
以上代码仅供参考,实际应用中需根据具体需求进行修改和完善。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)