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

Next.js 13.4客户端侧数据获取失败问题求助

问题排查与解决方案

你的代码里存在一个关键错误,导致请求失败:

1. fetch调用未添加await

fetch 是异步函数,你在 getData 里直接赋值 const res = fetch(...) 得到的是一个Promise对象,而非实际的响应实例。此时访问 res.ok 会得到 undefined,触发 !res.ok 的判断,抛出错误。

修正后的代码:

'use client';

async function getData() {
  try{
    // 添加await获取实际响应对象
    const res = await fetch(`http://localhost:1337/api/posts`);

    if (!res.ok) {
      throw new Error('Failed to fetch data');
    }

    return res.json();

  } catch (err) {
    console.log(err);
  }
}

export default async function Home() {
  const posts = await getData()
  console.log(posts)

  return (
    <main className="flex min-h-screen flex-col items-center justify-between p-5">
    </main>
  )
}

2. 其他可能的排查点

如果修正后仍报错,检查以下内容:

  • Strapi的CORS配置:确保Strapi允许Next.js所在域名(默认是http://localhost:3000)的跨域请求。在Strapi的config/middlewares.js里,修改cors配置的origin为["http://localhost:3000"]或true(仅开发环境使用)。
  • Strapi的权限设置:确认posts内容类型的find权限已开启(在Strapi后台的「设置→角色与权限→公共角色→权限」中勾选对应权限)。
  • 端口与路径正确性:确认Strapi确实运行在1337端口,接口路径/api/posts配置正确(比如Strapi的内容类型slug是否为posts)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 03:54:57