javascript - 如何使用 json-server 保存时间戳?
问题描述
我一直在使用 json-server 和一个简单db.json
的来模拟我的 REST API。
但是,我现在需要在后端的每个 POST 上保存当前日期。
我希望 json-server 在每个 POST 上生成一个时间戳并将其保存在 db.json 中,因此每次我执行 GET 请求时,它都会响应记录的保存日期。
例如从这里开始:
{
"posts": [
{
"id": 1,
"title": "json-server",
"author": "typicode"
}
],
"comments": [
{
"id": 1,
"body": "some comment",
"postId": 1
}
]
}
对此:
{
"posts": [
{
"id": 1,
"title": "json-server",
"author": "typicode"
}
],
"comments": [
{
"id": 1,
"body": "some comment",
"postId": 1,
"timeSaved": "2020-09-17T09:15:27+00:00"
}
]
}
解决方案
您可以json-server
与 Express 中间件结合使用作为模块:https ://github.com/typicode/json-server#module 。
他们有一个示例可以为 POST 请求保存 createdAt:
server.use((req, res, next) => {
if (req.method === 'POST') {
req.body.createdAt = Date.now()
}
// Continue to JSON Server router
next()
})
或者您可以使用我的 API 服务器(基于 json-server):https ://github.com/robinhuy/fake-rest-api-nodejs
推荐阅读
- powerbi - 为什么措施不起作用:在power bi中更改策略编号时重新开始计数?
- windows - if/else 语句查看是否在特定窗口期间安装了 Windows 更新
- excel - 如何使用 VBA 加速 Excel 公式?
- c# - 如何将字符串从 C++ 原生传递到 C# Unity?
- python - 在 Seaborn 中设置默认饱和度
- java - 何时在 Cassandra 中使用 UUID 而不是毫秒时间戳?
- algorithm - 在 Python 上实现 Miller-Rabin 算法
- android - 如何检查android手机中是否可以使用显示在其他应用程序上的功能
- kubernetes - kubectl - 错误:您必须登录到服务器(服务器已要求客户端提供凭据)
- android-emulator - Android 模拟器 - 无法重置您设备上的状态