【问题标题】:("[object Promise]") cannot be serialized as JSON("[object Promise]") 不能序列化为 JSON
【发布时间】:2021-06-15 18:34:47
【问题描述】:

完全错误:

错误:在“/”中序列化从 getStaticProps 返回的 .b 时出错。 原因:object("[object Promise]") 无法序列化为 JSON。 请仅返回 JSON 可序列化数据类型。

我正在尝试调用从 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;
    }
}

【问题讨论】:

  • await WordpressService.getPageByIdTest(50);?

标签: javascript reactjs http fetch


【解决方案1】:

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

错误:从getStaticProps 返回了其他密钥。特性 用于您的组件的必须嵌套在 props 键下,例如

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 的评论看起来是正确的 - 等待结果,然后在我的情况下,我还必须等待来自 node-fetch 的 json 结果,以便承诺正确完成。

【讨论】:

    猜你喜欢
    • 2021-04-17
    • 2020-04-02
    • 2021-06-14
    • 1970-01-01
    • 2016-08-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多