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

Next.js 13.4构建静态页面调用Strapi API报错及解决

问题描述

在Next.js 13.4中构建加载快、SEO友好的静态页面时,需要从Strapi这类外部API获取数据。之前在Next.js 12中使用getStaticProps能正常获取数据,但改用官方推荐的服务器组件async/await写法后,抛出TypeError: fetch failed错误。API在浏览器中可正常访问,添加try/catch后发现是IPv6地址::1:1337连接被拒绝,最终将环境变量MY_STRAPI_URL中的localhost替换为127.0.0.1解决了问题。

代码示例

async function getData() {
  const res = await fetch(`${process.env.MY_STRAPI_URL}/api/works`);

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

  return res.json();
}

export default async function Home() {
  const works = await getData();
  
  return (
    <main className="flex min-h-screen flex-col items-center justify-between p-5">
      <div>
        {works && works?.data.map((item, i) => (
          <div key={i}>
              {item.attributes.Title}
          </div>
        ))}
      </div>
    </main>
  )
}

报错信息

TypeError: fetch failed
    at Object.fetch (node:internal/deps/undici/undici:11118:11)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5) {
  cause: Error: connect ECONNREFUSED ::1:1337
      at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1300:16)
      at TCPConnectWrap.callbackTrampoline (node:internal/async_hooks:130:17) {
    errno: -4078,
    code: 'ECONNREFUSED',
    syscall: 'connect',
    address: '::1',
    port: 1337
  }
}
原因分析
  • Next.js 13.4的服务器组件运行在Node.js环境中,Node.js解析localhost时优先尝试IPv6地址::1,但Strapi服务可能仅绑定了IPv4地址(127.0.0.1),未监听IPv6端口,导致连接被拒绝。
  • 浏览器解析localhost时会同时尝试IPv4和IPv6,能自动 fallback 到可用地址,因此浏览器中可正常访问API。
解决方法

将环境变量MY_STRAPI_URL中的localhost替换为127.0.0.1,强制Node.js使用IPv4连接Strapi服务:

原环境变量:

MY_STRAPI_URL=http://localhost:1337

修改后:

MY_STRAPI_URL=http://127.0.0.1:1337

修改后服务器组件的fetch请求将指向IPv4地址,避免IPv6连接被拒的问题。

内容的提问来源于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 05:05:13