我正在尝试从Next中的API获取数据。js应用程序使用getStaticProps()或getServerSideProps(),但数据没有被提取并显示在我的应用程序中。当我在组件内部使用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>
</>
);
}
当我加载页面时,我得到了fetch失败和500内部服务器错误,我的API端点没有错误。
是什么导致了这个问题,我该如何解决它?
我想使用nextjs中的getStaticProps或getServerSideProps获取来自API端点的学生列表。
1条答案
按热度按时间ioekq8ef1#
getStaticProps在构建应用程序时发生。
呈现页所需的数据在用户请求之前的生成时可用
因此,请确保http://localhost:8000/在此期间可用。
https://nextjs.org/docs/basic-features/data-fetching/get-static-props