【问题标题】:Error: How to serialize data from getStaticProps : Next.js错误:如何从 getStaticProps 序列化数据:Next.js
【发布时间】:2021-05-12 08:42:45
【问题描述】:

我正在使用 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 获取所有业务配置文件:

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]”中的getStaticProps 返回的.profileData 时出错。 原因:undefined 无法序列化为 JSON。请使用null 或省略此值。

我不知道是什么原因造成的。

【问题讨论】:

  • 重复我在上一个问题中提到的内容:allProfiles 对象中的某些字段是undefined,它不能作为 JSON 序列化,因此无法从 getStaticProps 返回。将它们转换为 null 或完全忽略它们。
  • 我将如何解决它?请
  • 我投票结束这个问题,因为同一个用户已经问过这个问题:stackoverflow.com/questions/66102884/…
  • 你修好了吗?
  • 我有同样的错误。你能解决它吗?

标签: javascript reactjs ecmascript-6 next.js


【解决方案1】:

在调用返回对象的异步函数时添加JSON.stringify

尝试像这样修改您的 getStaticProps 函数。

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

    return {
        props: {
             allProfiles
        }
   };
}

JSON.stringify() 方法将 JavaScript 对象或值转换为 JSON 字符串,如果指定了替换函数,则可选择替换值,如果指定了替换数组,则可选择仅包含指定的属性。

来源:MDN

【讨论】:

    【解决方案2】:

    我在使用 Mongoose 和 Next.js 时遇到了这个问题。

    为了解决这个问题:我从 convert require 切换到 import 然后将结果包装在 JSON.parse(JSON.stringify(result)); 中。

    好: import mongoose from 'mongoose';

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

    【讨论】:

      【解决方案3】:

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

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

      error:undefined 导致了错误。因为“未定义”无法序列化:

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

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

      【讨论】:

      • 我试图从getStaticProps 导出布尔值context.preview,而每当我退出预览模式时,该值就会出现undefined。我只是返回了!!context.preview,错误就解决了。
      【解决方案4】:

      我在访问getStaticProps 中的 Vercel 系统环境变量时遇到了同样的序列化错误。

      使用JSON.stringify 没有成功,但String() 有效。我的代码:

      export async function getStaticProps() {
        const deploymentURL = String(process.env.NEXT_PUBLIC_VERCEL_URL);
      
        return {
          props: {
            deploymentURL,
          },
        };
      }
      

      感谢this GitHub issue 的启发

      【讨论】:

        【解决方案5】:

        试试这个,它对我有用:

        export async function getStaticProps() {
          const APP_URL = process.env.PUBLIC_NEXT_WEB_APP_URL;
          const res = await fetch(`${APP_URL}/api/projects`);
          const projects = await res.json();
          return {
            props: {
              projects: projects?.data,
            },
          };
        }
        

        【讨论】:

          【解决方案6】:

          我在尝试使用 id 在数据数组中查找匹配项时遇到了同样的问题。我遇到的问题是数组中的项目的 id 是数字,而我从 params 获得的值是一个字符串。所以我所做的就是将数字 id 转换为字符串以匹配比较。

          export async function getStaticProps({ params }) {
            const coffeeStore = coffeeStoreData.find(
              (store) => store.id.toString() === params.slug[0]
            );
            return {
              props: {
                coffeeStore,
              },
            };
          }

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2021-06-22
            • 2021-06-19
            • 2023-03-06
            • 2021-06-23
            • 1970-01-01
            • 1970-01-01
            • 2023-04-03
            相关资源
            最近更新 更多