You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用json-server获取指定ID的note时返回404错误求助

GET请求获取指定ID的note返回404错误(json-server)

问题描述

使用json-server搭建本地API后,访问http://localhost:3200/notes可正常获取全部note数据,但通过http://localhost:3200/notes/2请求指定ID的note时,所有API客户端(POSTMAN、INSOMNIA、THUNDER CLIENT)均返回404错误。

已执行操作:

  • 全局安装json-server:npm install -g json-server
  • 启动服务:json-server --watch db.json -p 3200

db.json内容:

{
  "notes": [
    {
      "title": "React - Props",
      "content": "Props are data I can send to a component. You can send any kind of data : Objects, strings, numbers, arrays, jsx...\nYou can never modify a props directly they are read-only. Any time a component props changes the component re-render.\n\nExample : \n\n<Component myProps=\"This is a props\" />",
      "created_at": "23/08/2022",
      "id": 2
    },
    {
      "title": "React - States",
      "content": "A state is a data managed by a component. Any time a component state changes the component re-render",
      "created_at": "23/08/2022",
      "id": 5
    },
    {
      "title": "React - Hooks",
      "content": "Hooks are function that let you use states and other React features. \n\nuseEffect() and useState() are two famous React hooks. ",
      "created_at": "23/08/2022",
      "id": 6
    }
  ]
}

可能的原因及解决办法

1. 版本兼容性问题

部分旧版本json-server对数字ID的路由匹配存在bug,更新到最新版本即可解决:

npm install -g json-server@latest

更新完成后重启服务,重新尝试访问目标URL。

2. 手动指定路由规则

先通过查询参数验证数据是否存在:

http://localhost:3200/notes?id=2

若该请求能返回正确数据,说明路由匹配逻辑异常。此时可创建routes.json文件自定义路由:

{
  "/notes/:id": "/notes?id=:id"
}

启动服务时指定路由文件:

json-server --watch db.json --routes routes.json -p 3200

再次访问http://localhost:3200/notes/2即可。

3. 重启服务确保数据加载正确

json-server的watch模式偶尔会出现文件变更未触发更新的情况,直接关闭服务后重新启动:

json-server --watch db.json -p 3200

4. 检查URL格式

确认请求URL没有多余空格或特殊字符,避免使用末尾带斜杠的格式(如http://localhost:3200/notes/2/)。

内容的提问来源于stack exchange,提问作者Kalyxos

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 12:03:40