Next.js 应用程序未使用 getStaticProps 或 getServerSideProps 从 API 获取数据

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

我尝试使用 getStaticProps() 或 getServerSideProps() 从 Next.js 应用程序中的 API 获取数据,但数据未在我的应用程序中获取和显示。当我在组件内部使用 fetch() 时,数据会被正确获取并显示,但我想使用服务器端渲染来提高性能和 SEO。 注意:我已经用 laravel 构建了我的 api,当我在 postman 中使用它时它可以工作。

export async function getStaticProps() {
  try {
    const response = await fetch('http://localhost:8000/api/students');
    const { data } = await response.json();

    return { props: { students: data } };
  } catch (error) {
    console.log(error);
    return { props: { students: [] } };
  }
}

这是我在组件中渲染数据的代码:

export default function StudentsPage({ students }) {
  return (
    <>
      <h1>Students</h1>

      <ul>
        {students.map((student) => (
          <li key={student.id}>
            {student.name} ({student.email})
          </li>
        ))}
      </ul>
    </>
  );
}

当我加载页面时,我收到获取失败和 500 内部服务器错误,但我的 api 端点没有错误。

什么可能导致此问题,如何解决?

我想使用 nextjs 中的 getStaticProps 或 getServerSideProps 获取来自我的 api 端点的学生列表。

laravel next.js
1个回答
2
投票

getStaticProps 在您构建应用程序时发生。

渲染页面所需的数据在构建时可用 用户的请求

因此请确保 http://localhost:8000/ 在此期间可用。

https://nextjs.org/docs/basic-features/data-fetching/get-static-props

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