【问题标题】:原因:`object` ("[object Date]") 无法序列化为 JSON。请仅返回 JSON 可序列化数据类型
【发布时间】:2022-01-23 16:19:37
【问题描述】:

我正在使用 prisma 和 Next.js。当我尝试从getStaticProps 中的 prisma 检索内容时,它确实会获取数据,但我无法将其传递给主要组件。

export const getStaticProps = async () => {
  const prisma = new PrismaClient();
  const newsLetters = await prisma.newsLetters.findMany();
  console.log(newsLetters);

  return {
    props: {
      newsLetters: newsLetters,
    },
  };
};

正如您在这张图片中看到的那样,它正在获取和打印内容。

但是当我通过时,我将它作为道具传递时出现以下错误

Reason: `object` ("[object Date]") cannot be serialized as JSON. Please only return JSON serializable data types.

【问题讨论】:

标签: javascript next.js prisma serializable


【解决方案1】:

出于性能原因,nextJS 似乎不喜欢序列化除标量类型之外的任何内容。您可以在此github issue 中阅读更多内容。处理此问题的最佳方法是在返回 Date 对象之前将它们转换为 UNIX 时间戳。

// your data
let newsLetters = [
    {
        id: 'your-id',
        email: 'email@example.com',
        createdAt: new Date()
    }
];

// map the array
newsLetters.map(x => {
    x.createdAt = Math.floor(x.createdAt / 1000);
    return x;
})

// use newsLetters now
console.log(newsLetters);

【讨论】:

    猜你喜欢
    • 2022-10-03
    • 1970-01-01
    • 2021-04-17
    • 1970-01-01
    • 2020-02-19
    • 2020-04-02
    • 2021-06-14
    • 2021-06-15
    • 1970-01-01
    相关资源
    最近更新 更多