首页 > 解决方案 > 如何使用 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"
    }
  ]
}

标签: javascriptjsonrestjson-server

解决方案


您可以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


推荐阅读