NextJS getStaticProps 中的 API 调用导致错误 500 [英] API call in NextJS getStaticProps causes error 500

查看:171
本文介绍了NextJS getStaticProps 中的 API 调用导致错误 500的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

getStaticProps 中进行的 API 调用似乎导致错误 500.

An API call made in getStaticProps seems to cause an error 500.

这是我的组件代码:

import React from "react";
import API from "services/api";

const ArtistListPage = (props) => {
    return (
        <>
            {props.artists.map((artist) => (
                <div key={artist.id}>{artist.first_name}</div>
            ))}
        </>
    );
};

export async function getStaticProps() {
    // Get external data from the file system, API, DB, etc.
    const res = await API.get("/get_artists");
    const artists = await res.data.json();
    return {
        props: { artists },
    };
}

export default ArtistListPage;

我想提一下 useEffect 中的相同 API 调用,以及将硬编码对象传递给 getStaticProps<中的 props/代码>.似乎只有 getStaticProps 中的 API 调用会导致问题.

I'd like to mention that the same API call in a useEffect works, as well as passing in a hard coded object to props in getStaticProps. Only the API call inside the getStaticProps seems to cause an issue.

有谁知道错误可能来自哪里以及如何解决它?

Does anyone know where the error could come from and how to solve it?

推荐答案

getStaticProps 在构建时执行,您无法调用自己的 API,因为 Next.js 服务器未运行.

getStaticProps is executed at a build time and you can't call your own API because Next.js server is not running.

您可以直接在 getStaticProps 中执行数据库查询或从文件系统中读取数据,而无需进行 API 调用.

You can execute DB queries or read from file system inside getStaticProps directly, without making an API call.

这篇关于NextJS getStaticProps 中的 API 调用导致错误 500的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆