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

React Fetch请求无法显示返回元素,Laravel接口后端正常

问题解决:Fetch请求后无法获取后端返回的数组

你遇到的问题核心是fetch函数返回的是Promise对象,而非直接的响应数据。直接打印这个Promise只能看到它的状态和Response对象,看不到后端返回的数组内容——Postman能正常获取是因为它自动完成了响应解析步骤,而React中需要你手动处理。

正确实现方式

方式1:使用.then()链式调用

fetch('http://127.0.0.1:8000/api/getlist')
  .then(response => {
    // 先校验响应是否成功
    if (!response.ok) {
      throw new Error('请求失败');
    }
    // 解析响应为JSON格式(后端返回的数组属于JSON类型)
    return response.json();
  })
  .then(data => {
    // 此处的data就是后端返回的数组
    console.log(data);
    // 可将data赋值给状态变量用于页面渲染
    // setList(data);
  })
  .catch(error => {
    // 处理请求或解析过程中的错误
    console.error('请求出错:', error);
  });

方式2:使用async/await(更简洁直观)

async function getList() {
  try {
    const response = await fetch('http://127.0.0.1:8000/api/getlist');
    if (!response.ok) {
      throw new Error('请求失败');
    }
    const data = await response.json();
    console.log(data);
    // setList(data);
  } catch (error) {
    console.error('请求出错:', error);
  }
}

// 调用函数发起请求
getList();

关键注意点

  • response.json()本身也返回Promise,必须等待它解析完成才能拿到实际的数组数据。
  • 必须添加错误处理逻辑,避免请求失败或解析失败时出现未捕获异常。
  • 如果后端返回的是纯文本而非JSON,可替换为response.text()方法解析。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 15:25:16