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

Laravel GET API返回数据在浏览器中无法获取字段值求助

问题解决:Laravel API返回数据前端无法获取嵌套字段

问题根源分析

从你提供的Postman和浏览器控制台输出可以看到两个核心问题:

  1. API返回了双层嵌套数组(外层数组包裹了资源集合返回的数组),导致前端直接遍历外层数组时,拿到的是内层数组而非订单对象。
  2. 你要获取的salary、age、name字段并非直接在订单对象下,而是嵌套在client子对象中。

分步修复

1. 修正Laravel Controller的返回格式

你的GetController里把资源集合额外包了一层数组,这是多余的——ValuesResource::collection()本身就会返回数组格式的集合数据。修改控制器代码:

function getValues()
{
    // 移除外层的[],直接返回资源集合
    return response()->json(ValuesResource::collection(Order::all()), 200);
}

修改后API返回的结构会变成单层数组:

[
    {
        "order_number": "b7f55e7ce5",
        "client_id": 1,
        "description": "order1",
        "client": {
            "name": "Mr. Omari Schaefer DVM",
            "age": "29",
            "salary": "150"
        }
    }
]

2. 修正前端代码的字段获取逻辑

现在前端拿到的是订单对象数组,需要从每个订单的client属性里提取目标字段:

async function getData() {
    const apiUrl = "http://127.0.0.1:8000/api/list";

    const response = await fetch(apiUrl)
    const barChatData = await response.json()
    console.log(barChatData);

    // 从每个订单的client对象中提取字段
    const salary = barChatData.map((order) => order.client.salary)
    const age = barChatData.map((order) => order.client.age)
    const name = barChatData.map((order) => order.client.name)

    employeeSalaryData = salary
    employeeAgeData = age
    employeeLabel = name
}

验证效果

修改后,前端控制台输出的salary、age、name数组会正确包含对应的值,不再返回undefined。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 04:39:34