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

完整错误:

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. Properties intended 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 正确完成。

https://stackoverflow.com/questions/66689741/

相关文章:

c# - 解析不同的HttpClient

python - 类型错误 : input expected at most 1 argument,

python - 在 pandas 的 to_markdown() 中抑制科学记数法

git - 有没有没有版本提交的 'bump the version' 的方法?

kotlin - 在 Kotlin 中定义数组类型

c - 将 foo(int *) 作为参数传递给 X 中的 foo(void*)

c# - UWP:导航 View 没有完全延伸到标题栏

Flutter - 'showSnackBar' 已弃用 - 如何更新?

Angular 11 - RouterModule - 'router-outlet' 不是已知元素

python - 有没有办法在这个正态分布的区域上色?