JSON 服务器和自定义路由
我正在使用 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为您在这里可以做的最好的事情就是使用该请求的参数处理。例如,您可以在您的情况下执行
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).