原因:`object` ("[object Date]") 无法序列化为 JSON。请仅返回 JSON 可序列化数据类型

Ric*_*rix 23 javascript serializable next.js prisma

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

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

  return {
    props: {
      newsLetters: newsLetters,
    },
  };
};
Run Code Online (Sandbox Code Playgroud)

正如您在此图中看到的,它正在获取并打印内容。

在此输入图像描述

但是当我通过时,我收到以下错误,将其作为道具传递

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

Aid*_*n53 28

如果您使用的是typescript,则无法将 的类型更改createdAt为字符串或数字,如下所示:

newsLetter.createdAt = newsLetter.createdAt.toString();
// Error: Type 'string' is not assignable to type 'Date'.
Run Code Online (Sandbox Code Playgroud)

相反,您可以在 JSON.parse 中使用 JOSN.stringfy 来创建可序列化对象:

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

  return {
     props: {
        newsLetters: JSON.parse(JSON.stringify(newsLetters)) // <===
     }
  }
}
Run Code Online (Sandbox Code Playgroud)


chi*_*t24 9

您可以使用Blitz 的superjson软件包来实现此功能。他们在https://github.com/blitz-js/superjson#using-with-nextjs上有说明:

与 Next.js 一起使用

getServerSidePropsNext.js 提供的、getInitialProps和data挂钩getStaticProps不允许您传输日期等 Javascript 对象。除非您将日期转换为字符串等,否则它将出错。

值得庆幸的是,Superjson 是绕过该限制的完美工具!

Next.js SWC 插件(实验性,v12.2 或更高版本)

Next.js SWC 插件是 实验性的,但承诺显着加速。要使用SuperJSON SWC 插件,请安装它并将其添加到您的next.config.js

yarn add next-superjson-plugin
Run Code Online (Sandbox Code Playgroud)
// next.config.js
module.exports = {
  experimental: {
    swcPlugins: [
      [
        'next-superjson-plugin',
        {
          excluded: [],
        },
      ],
    ],
  },
} 
Run Code Online (Sandbox Code Playgroud)


小智 8

出于性能原因,看起来 nextJS 不喜欢序列化除标量类型之外的任何内容。您可以在这个github 问题中阅读更多内容。处理此问题的最佳方法是在返回 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);
Run Code Online (Sandbox Code Playgroud)