JSON 服务器和自定义路由

发布于 2025-01-13 18:26:35 字数 532 浏览 3 评论 0原文

我正在使用 JSON 服务器。如果我使用 npx json-server --watch database.json --port 5000 初始化它,然后打开 http://localhost:5000/items 我可以看到所有项目。如果我访问 http://localhost:5000/items/1 我只有一项。我的问题是 - 如何更改单个项目路由,以便通过输入 http://localhost:5000/items/myCustomId1 获取第一个项目?换句话说,如何用 customId 替换 id

{
  "items": [
    {
      "id": 1,
      "customId": "myCustomId1",
      "name": "Item 1"
    },
    {
      "id": 2,
      "customId": "myCustomId2",
      "name": "Item 2"
    }
  ]
}

I'm using JSON server. If I initialize it with npx json-server --watch database.json --port 5000 and then open http://localhost:5000/items I can see all the items. If I go to http://localhost:5000/items/1 I have only one item. My question is - how can I change single item route so I get the first item by entering http://localhost:5000/items/myCustomId1? In other words, how can I replace id with customId?

{
  "items": [
    {
      "id": 1,
      "customId": "myCustomId1",
      "name": "Item 1"
    },
    {
      "id": 2,
      "customId": "myCustomId2",
      "name": "Item 2"
    }
  ]
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

凡间太子 2025-01-20 18:26:35

我认为您在这里可以做的最好的事情就是使用该请求的参数处理。例如,您可以在您的情况下执行 http://localhost:5000/items?myCustomId=1 。这可能会列出 customId 为 1 的所有项目,而不是仅列出 1 个项目(因为在这种情况下,customId 不是唯一的)。

I think the best you can do here is using parameters handling for that request. For instance, you can do http://localhost:5000/items?myCustomId=1 in your case. This will probably list all the items with customId of 1 instead of just 1 item (since customId is not unique in this case).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文