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

Ade*_*ect 8 javascript ecmascript-6 reactjs 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.
Run Code Online (Sandbox Code Playgroud)

我的代码:

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
      }
    };
  }
Run Code Online (Sandbox Code Playgroud)

来自 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;
};
Run Code Online (Sandbox Code Playgroud)

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

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

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

小智 21

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

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

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

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

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

来源:MDN


Jos*_*shu 5

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

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

好的: import mongoose from 'mongoose';

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


Yil*_*maz 3

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

const INITIAL_STATE = {
  products: [],
  loading: false,
  error: undefined,
  cart: [],
};
Run Code Online (Sandbox Code Playgroud)

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

export async function getStaticProps() {
    const allProfiles = await getAllBusinessProfiles();
    return {
      props: {
        allProfiles
      }
    };
  }
Run Code Online (Sandbox Code Playgroud)

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