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

如何在Vue.js中用JSON Server访问JSON对象内的评论数组?

解决JSON Server访问嵌套评论数组404的问题

你的404问题根源在于JSON Server的路由规则和当前的数据结构不匹配,以下是两种可行的解决方法:

方法1:调整JSON数据结构(推荐)

JSON Server需要顶层为集合数组才能支持嵌套资源路由。把单个产品对象放到products数组中,修改后的JSON如下:

{
  "products": [
    {
      "id": 1,
      "name": "Product A",
      "description": "This is a great product.",
      "reviews": [
        {
          "id": 1,
          "rating": 4,
          "comment": "I really like this product."
        },
        {
          "id": 2,
          "rating": 5,
          "comment": "This product exceeded my expectations!"
        },
        {
          "id": 3,
          "rating": 3,
          "comment": "This product is okay, but I've had better."
        }
      ]
    }
  ]
}

重启JSON Server后,访问http://localhost:3000/products/1/reviews就能直接获取该产品的评论数组。

方法2:不修改结构,通过根路径获取后提取评论

如果不想调整数据结构,直接访问根路径获取完整产品对象:

GET http://localhost:3000/

拿到返回结果后,在前端代码中提取reviews字段即可。若顶层存在多个产品,也可用查询参数过滤目标产品:

GET http://localhost:3000/?id=1

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 14:52:37