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

时间:2019-07-12 10:25:46

标签: javascript json-server

我使用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"
  }
]

但是我有这个错误

  

错误:糟糕,在数据库属性“ playbook / active”中找到了/字符。

我更改为“剧本/有效”,但错误相同

3 个答案:

答案 0 :(得分:1)

检查错误消息:

  

糟糕,在数据库属性“ dossier / la”中找到/字符。

     不支持

/,如果要调整默认路由,请参见
  https://github.com/typicode/json-server/#add-custom-routes

似乎不支持斜杠。

解决方案是创建一个包含您的网址映射的routes.json文件。

例如,此文件的内容可能是:

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

答案 1 :(得分:1)

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

配置 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"
}
<块引用>

注意:routes.json 中的映射是这样的:[expanded/endpoint]: aliasEndpoint 其中 aliasEndpoint 应该与 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

示例

GET → http://localhost:3000/playbook/active

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

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

GET → http://localhost:3000/playbook/active/2

响应包含与 id=2 匹配的活动剧本

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

答案 2 :(得分:0)

例如:

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