1

我正在尝试让Json-Server (v 0.12.1) 在不需要中间件或将其用作组件的情况下工作 - 如果我要花时间手动编码所有端点,我已经有了一些可以正常工作的东西. 我被简单的路由配置所吸引,我相信我应该能够使用它而不需要任何东西,只需要一个routes.jsonand db.json(让我删除很多样板快递的东西)。

我的 db.json:

  "users": [
    {
      "userId": 1,
      "favoriteColor": "red"
    },
    {
      "userId": 2,
      "favoriteColor": "blue"
    },
    {
      "userId": 3,
      "favoriteColor": "green"
    }
  ]

我的路线.json:

{
    "/api/users": "/users",
    "/api/users/:userId": "/users/:userId"
}

我希望能够进行 GET 调用:http://localhost:3000/api/users/2并获取

{
  "userId": 2,
  "favoriteColor": "blue"
}

作为回报。但是,我总是得到{}.

尝试使用来自 SO 的一些建议来更改数据结构(我无法控制)或使用过滤器(返回数组,而不是对象)对我来说是不行的。

有谁知道为什么这条看似简单的路线行不通?我相信我正在遵循自定义路线指南。我用 启动服务器json-server --watch ./api/db.json --routes ./api/routes.json,点击http://localhost:3000/api/users返回的正是我所期望的,所以我知道routes.json文件和db.json文件都被成功拾取。

谢谢!

4

1 回答 1

1

我必须通过以下方式启动服务器: json-server --watch db.json --routes routes.json

db.json

{
  "users": [
    {
      "id": 1,
      "first_name": "Sebastian",
      "last_name": "Eschweiler",
      "email": "sebastian@codingthesmartway.com"
    },
    {
      "id": 2,
      "first_name": "Steve",
      "last_name": "Palmer",
      "email": "steve@codingthesmartway.com"
    },
    {
      "id": 3,
      "first_name": "Ann",
      "last_name": "Smith",
      "email": "ann@codingthesmartway.com"
    }
  ]
}

路线.json

{
    "/api/users": "/users",
    "/api/users/:id": "/users/:id"
}
于 2017-11-16T18:27:19.933 回答