json-server db.json 中带有“/”的路径

Path with '/' in json-server db.json

我用server-json来伪造API,我在data.json

中有路径"playbook/active"
"playbook/active": [{
    "description": "This playbook will install haproxy",
    "name": "Testing playbook 3",
    "tag": [
      "loadbalancer",
      "charge"
    ],
    "path": "/etc/ansible/haproxy.yml",
    "type": "action",
    "id": "4bb107be-9efe-11e9-b3e5-bc5ff4901aa5"
  },
  {
    "path": "google.com",
    "description": "This is the playbook before execution",
    "tag": [
      "webserver",
      "tomcat"
    ],
    "id": "faa746b4-9cb7-11e9-9b94-bc5ff4901aa5",
    "name": "mysql"
  }
]

但是我有这个错误

Error: Oops, found / character in database property 'playbook/active'.

我改成"playbook/active"但同样的错误

检查错误信息:

Oops, found / character in database property 'dossier/la'.

/ aren't supported, if you want to tweak default routes, see
https://github.com/typicode/json-server/#add-custom-routes

好像不支持斜杠。

解决方案是创建一个 routes.json 文件,其中包含 url 的映射。

例如这个文件的内容可以是:

{
  my-awesome-endpoint": "playbook/active"
}

例如:

db.json

    "list": [
        {
            "name": "abcde",
            "tel": "123454323",
            "id": 5
        }
    ]

routes.json

{
    "/v1/list?type=hot": "/list"
}

开始命令:

npx json-server --watch db.json --routes routes.json

提供完整答案(展示示例)

配置 db.jsonroutes.json 可以为您解决问题:

  • db.json
{
    "playbookActive": [
        {
            "id": 1,
            "name": "Active Playbook 1",
            "description": "Description 1"
        },
        {
            "id": 2,
            "name": "Active Playbook 2",
            "description": "Description 2"
        }
    ]
}

routes.json

{
    "/playbook/active": "/playbookActive",
    "/playbook/active/:id": "/playbookActive/:id"
}

Note: the mapping in routes.json is goes like this: [expanded/endpoint]: aliasEndpoint where aliasEndpoint should match the one from db.json.

package.json

{
    ...
    "scripts": {
        "api": "json-server [path-to-db.json] --routes [path-to-routes.json] --no-cors=false"
    },
    ...
}

启动时验证路由(来自 npm run api 的日志):

Resources
http://localhost:3000/playbookActive

Other routes
/playbook/active -> /playbookActive
/playbook/active/:id -> /playbookActive/:id

Home
http://localhost:3000

例子

获取 → http://localhost:3000/playbook/active

响应包含一个包含所有活动剧本的列表:

[
  {
    "id": 1,
    "name": "Active Playbook 1",
    "description": "Description 1"
  },
  {
    "id": 2,
    "name": "Active Playbook 2",
    "description": "Description 2"
  }
]

获取 → http://localhost:3000/playbook/active/2

响应包含匹配 id=2:

的活动剧本
{
  "id": 2,
  "name": "Active Playbook 2",
  "description": "Description 2"
}