gpt4 book ai didi

javascript - ("[object Promise]") 无法序列化为 JSON

转载 作者:行者123 更新时间:2023-12-05 09:34:23 28 4
gpt4 key购买 nike

完整错误:

Error: Error serializing .b returned from getStaticProps in "/".Reason: object ("[object Promise]") cannot be serialized as JSON.Please only return JSON serializable data types.

我正在尝试调用我的一个函数,该函数从 API 端点检索一些数据,但是在尝试将此数据传递给 props 时出现错误。我不完全确定我做错了什么,因为如果 fetch 调用在 GetStaticProps 中,但我希望我所有的 fetch 调用逻辑都存在于一个单独的 js 页面中以减少冗余,但是这样做会产生这个错误。

export async function getStaticProps() {

let b = WordpressService.getPageByIdTest(50);

return {
props: {
b: b,
},
revalidate: 30
}

const WordpressService = {
async getPageByIdTest(id) {

const resIndexPage = await fetch(`${url}pages/${id}`);
const indexPageData = await resIndexPage.json();

return indexPageData;
}
}

最佳答案

我正在查看最新版本的 nextjs,我确实注意到当我运行该演示时它很奇怪。具体来说,我在运行他们的示例时遇到了这个错误:

Error: Additional keys were returned from getStaticProps. Propertiesintended for your component must be nested under the props key, e.g.

export async function getSortedPostsData() {
// Instead of the file system,
// fetch post data from an external API endpoint
const res = await fetch('..')
return res.json()
}

这不完全是您的问题,但通过 res.json() 分配 props 对象也会导致您遇到同样的错误。

因此,对我来说,使用节点 15 我将 api 调用更改为:

export async function getStaticProps() {
const url = `https://my-url`
const result = await fetch(url)
return { props: {
result: await result.json()
}}
}

这解决了我的问题。所以 Ivar 的评论看起来是正确的 - 等待结果,然后在我的情况下,我还必须等待来自节点获取的 json 结果,以便 promise 正确完成。

关于javascript - ("[object Promise]") 无法序列化为 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66689741/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com