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

IT技术 javascript reactjs ecmascript-6 next.js
2021-05-10 15:57:15

我正在使用 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 方法,但得到了上面的错误。请检查。谢谢。

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

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

4个回答

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

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

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

    return {
        props: {
             allProfiles
        }
   };
}

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

来源:MDN

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

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

好的: import mongoose from 'mongoose';

坏的: const mongoose = require('mongoose');

我在使用 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”,这是异步的结果,getAllBusinessProfiles()它返回未定义、错误或返回对象的字段之一未定义。“错误”对象在javascript中不可序列化

getStaticProps.

使用JSON.stringify并没有解决问题,但String()有效。我的代码:

export async function getStaticProps() {
  const deploymentURL = String(process.env.NEXT_PUBLIC_VERCEL_URL);

  return {
    props: {
      deploymentURL,
    },
  };
}

感谢这个 GitHub issue的启发