错误:无法在 Next.js 13.4 上获取数据

问题描述 投票:0回答:1

我是 Next.js 12 的长期用户,之前从未遇到过它的文档问题, 刚刚尝试了新的 Next.js 13.4 并想向我本地托管的 strapi 添加一个简单的客户端 api 调用:

page.js

'use client';

async function getData() {
  try{
    const res = 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>
  )
}

但是它抛出

Error: Failed to fetch data
。 我显然首先在浏览器中测试了
http://localhost:1337/api/posts
url,它正确返回了 json。 所以有人知道发生了什么事吗? Next.js 文档说以这种方式调用提取。

next.js
1个回答
1
投票

在 Next.js 13.4 中,fetch 的默认行为发生了变化,它不再自动 resolve promises。

我修改了代码,所以函数可以处理承诺

async function getData() {
  try {
    const res = await fetch(`http://localhost:1337/api/posts`);

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

    return await res.json();
  } catch (err) {
    console.log(err);
  }
}

© www.soinside.com 2019 - 2024. All rights reserved.