错误:如何从 getStaticProps 序列化数据:Next.js

时间:2021-02-08 17:52:56

标签: javascript reactjs ecmascript-6 next.js

我正在使用 Next.js,我尝试访问数据但出现此错误:

Error: Error serializing `.profileData` returned from `getStaticProps` in "/profile/[slug]".
Reason: `undefined` cannot be serialized as JSON. Please use `null` or omit this value.

我的代码:

import { getAllBusinessProfiles } from '../../lib/api';

const Profile = ({ allProfiles: { edges } }) => {
    return ( 
        <>
          <Head>
            <title>Profile</title>
          </Head>

          <Hero />

          <section>
            {edges.map(({ node }) => (
              <div key={node.id}>
                  <Link href={`/profile/${node.slug}`}>
                    <a> {node.businessInfo.name} </a>
                  </Link>
              </div>
            ))}
          </section>

        </>
     );
}
 
export default Profile;

export async function getStaticProps() {
    const allProfiles = await getAllBusinessProfiles();
    return {
      props: {
        allProfiles
      }
    };
  }

来自 api.js 的 getAllBusinessProfiles:

const API_URL = process.env.WP_API_URL;

async function fetchAPI(query, { variables } = {}) {
  const headers = { 'Content-Type': 'application/json' };

  const res = await fetch(API_URL, {
    method: 'POST',
    headers,
    body: JSON.stringify({ query, variables })
  });

  const json = await res.json();
  if (json.errors) {
    console.log(json.errors);
    console.log('error details', query, variables);
    throw new Error('Failed to fetch API');
  }
  return json.data;
}

export async function getAllBusinessProfiles() {
    const data = await fetchAPI(
      `
      query AllProfiles {
        businessProfiles(where: {orderby: {field: DATE, order: ASC}}) {
          edges {
            node {
              date
              title
              slug
              link
              uri
              businessInfo {
                name
                title
                company
                image {
                  mediaItemUrl
                  altText
                }
                highlight
                phone
                city
                country
                facebook
                instagram
                email
                website
                profiles {
                  profile
                  profileInfo
                }
                extendedProfile {
                  title
                  info
                }
              }
            }
          }
        }
      }
      
      `
    );
    return data?.businessProfiles;
};

这里可能有什么错误?我在 Next.js 上使用了 getStaticProps 方法,但得到了上面的错误。请检查。谢谢。

错误: 服务器错误 错误:序列化从“/profile/[slug]”中的 .profileData 返回的 getStaticProps 时出错。 原因:undefined 无法序列化为 JSON。请使用 null 或省略此值。

我不知道是什么导致了这种情况。

3 个答案:

答案 0 :(得分:4)

<块引用>

在调用返回对象的异步函数时添加 JSON.stringify。 尝试像这样修改 getStaticProps 函数。

export async function getStaticProps() {
    const profiles = await getAllBusinessProfiles();
    const allProfiles = JSON.stringify(profiles)

    return {
        props: {
             allProfiles
        }
   };
}

答案 1 :(得分:1)

我在使用 redux 和 next js 时遇到了同样的问题,原因是我将其设置为未定义的默认状态的字段之一:

const INITIAL_STATE = {
  products: [],
  loading: false,
  error: undefined,
  cart: [],
};

error:undefined 导致错误。因为“未定义”不能被序列化:

export async function getStaticProps() {
    const allProfiles = await getAllBusinessProfiles();
    return {
      props: {
        allProfiles
      }
    };
  }

您正在返回“allProfiles”,这是 async getAllBusinessProfiles() 的结果,它返回未定义、错误或返回对象的字段之一未定义。 “错误”对象在 javascript 中不可序列化

答案 2 :(得分:0)

我在使用 Mongoose 和 Next.js

时遇到了这个问题

为了解决它:我从 convert require 切换到 import 然后将我的结果包装在 JSON.parse(JSON.stringify(result));

好: 从'猫鼬'导入猫鼬;

不好: const mongoose = require('mongoose');