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

使用json-server自定义路由时出现404错误的问题咨询

json-server 0.17.0路由配置404问题排查

需求与问题

我正在学习使用json-server(版本0.17.0),希望通过URL http://localhost:3001/getFolderByFolderId/14 获取folder_id为14的文件夹数据,目标数据结构如下:

{
  "folder_id": 14,
  "abstracts": {
    "33": {
      "abstract_name": "abstractt1"
    },
    "34": {
      "abstract_name": "abstract2"
    },
    "35": {
      "abstract_name": "abstract3"
    }
  },
  "folder_name": "folder2",
  "number_of_items": 2,
  "user_id": 6
}

当前配置及问题:

  • 执行启动命令:json-server --watch db.json --routes route.json --port 3001
  • 访问http://localhost:3001/folders?folder_id=14可正常得到200响应,但访问http://localhost:3001/getFolderByFolderId/14出现404错误
  • 尝试将db.json中的folders改为数组形式,问题仍存在

当前配置文件内容

初始db.json

{
  "folders": {
    "folder_id": 14,
    "abstracts": {
      "33": {
        "abstract_name": "abstractt1"
      },
      "34": {
        "abstract_name": "abstract2"
      },
      "35": {
        "abstract_name": "abstract3"
      }
    },
    "folder_name": "folder2",
    "number_of_items": 2,
    "user_id": 6
  }
}

route.json

{
  "routes": {
    "/getFolderByFolderId/:id": "/folders?folder_id=:id"
  }
}

修改后的数组形式db.json

{
  "folders": [{
    "folder_id": 14,
    "abstracts": {
      "33": {
        "abstract_name": "abstractt1"
      },
      "34": {
        "abstract_name": "abstract2"
      },
      "35": {
        "abstract_name": "abstract3"
      }
    },
    "folder_name": "folder2",
    "number_of_items": 2,
    "user_id": 6
  }]
}

问题原因及解决方法

  • 路由文件格式错误:json-server的路由配置文件不需要外层的"routes"包裹,直接写路由映射键值对即可。多余的外层对象导致路由规则无法被正确解析。
  • URL端口遗漏:之前访问的URL未包含3001端口,正确地址应为http://localhost:3001/getFolderByFolderId/14。
  • 数据结构适配:使用查询参数?folder_id=:id时,folders需为数组形式(你修改后的版本符合要求),json-server对数组的查询支持更完善,单个对象结构无法适配查询参数逻辑。

修正后的配置

route.json

{
  "/getFolderByFolderId/:id": "/folders?folder_id=:id"
}

db.json(保持数组形式)

{
  "folders": [{
    "folder_id": 14,
    "abstracts": {
      "33": {
        "abstract_name": "abstractt1"
      },
      "34": {
        "abstract_name": "abstract2"
      },
      "35": {
        "abstract_name": "abstract3"
      }
    },
    "folder_name": "folder2",
    "number_of_items": 2,
    "user_id": 6
  }]
}

验证步骤

  1. 重启json-server服务
  2. 访问http://localhost:3001/getFolderByFolderId/14,即可正常返回目标数据

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 02:06:03