【问题标题】:Data is not fetching properly in SSG Next.jsSSG Next.js 中的数据未正确获取
【发布时间】:2023-01-31 23:48:35
【问题描述】:

在创建帖子(用于博客)时使用编辑器,我曾经直接将它的输出(html string)保存到mongo中。

然后在添加 SSG 之后,在构建时,(控制台)获取的数据显示为 this

而只需获取 api 即可正确显示数据。 here

代号获取静态道具&获取静态路径


export async function getStaticProps({ params }) {
    try {
        const { data } = await axios.post(baseUrl + getPostBySlug, { slug: params?.slug });

        console.log({ slug: params?.slug }, 'data 2 ->', data);    // here is the data consoled

        return {
            props: { post: data?.data ?? null },
            revalidate: 10,
        }
    }
    catch (err) {
        return {
            props: { post: null },
            revalidate: 10,
        }
    }
}

export async function getStaticPaths() {
    try {
        const res = await fetch(baseUrl + getAllPosts, { method: 'GET' });
        const data = await res?.json();

        if (data?.success && data?.data) {
            return {
                paths: data?.data?.map(({ slug }) => ({ params: { slug } })),
                fallback: true,
            }
        }
        else {
            return {
                paths: [{ params: { slug: '/' } }],
                fallback: true,
            }
        }
    }
    catch (err) {
        return {
            paths: [{ params: { slug: '/' } }],
            fallback: true,
        }
    }
}

最终输出,一个 SSG 页面但没有数据初始化 -> here

【问题讨论】:

  • 在返回之前尝试在你的getStaticPropsconsole.log(data?.data)
  • @AhmedSbai 是的,我在 getStaticProps 的第二行安慰了它。

标签: next.js static-site-generation


【解决方案1】:

您需要更新到 Axios ^1.2.1 - there was an issue with previous versions

您可以将标头设置为临时解决方案,以防止这种情况发生。

await axios.post("your/api/url",{
 headers: { Accept: 'application/json', 'Accept-Encoding': 'identity' },
 { slug: "url-slug" }
)

【讨论】:

    猜你喜欢
    • 2020-10-29
    • 2023-03-15
    • 2021-07-05
    • 2021-12-01
    • 2021-09-16
    • 2021-08-27
    • 2012-12-29
    • 2020-09-23
    • 1970-01-01
    相关资源
    最近更新 更多