简体   繁体   English

错误:如何序列化来自 getStaticProps 的数据:Next.js

[英]Error: How to serialize data from getStaticProps : Next.js

I'm working with Next.js, I tried accessing data but got this error:我正在使用 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.

My code:我的代码:

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
      }
    };
  }

getAllBusinessProfiles from api.js:从 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;
};

What could be the error here?这里可能是什么错误? I used the getStaticProps method on Next.js but got the error above instead.我在 Next.js 上使用了 getStaticProps 方法,但得到了上面的错误。 Please, check.请检查。 Thanks.谢谢。

The error: Server Error Error: Error serializing .profileData returned from getStaticProps in "/profile/[slug]".错误:服务器错误错误:序列化从“/profile/[slug]”中的getStaticProps返回的.profileData时出错。 Reason: undefined cannot be serialized as JSON. Please use null or omit this value.原因: undefined不能序列化为JSON,请使用null或省略该值。

I don't know what could cause this though.我不知道是什么原因造成的。

Add JSON.stringify when calling an asynchronous function that returns an object.在调用返回 object 的异步 function 时添加JSON.stringify

Try modifying your getStaticProps function like this.尝试像这样修改您的getStaticProps function。

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

    return {
        props: {
             allProfiles
        }
   };
}

The JSON.stringify() method converts a JavaScript object or value to a JSON string, optionally replacing values if a replacer function is specified or optionally including only the specified properties if a replacer array is specified. The JSON.stringify() method converts a JavaScript object or value to a JSON string, optionally replacing values if a replacer function is specified or optionally including only the specified properties if a replacer array is specified.

Source: MDN来源: MDN

I had the same issue when I was working with redux with next js and the reason was one of the fields in the default state I set it to undefined:我在使用带有下一个 js 的 redux 时遇到了同样的问题,原因是默认 state 中的字段之一我将其设置为未定义:

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

error:undefined was causing the error. error:undefined导致错误。 Because "undefined" cannot be serialized:因为“未定义”不能被序列化:

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

you are returning "allProfiles" which is the result of async getAllBusinessProfiles() which is either returning undefined, error or one of the fields of the returned object is undefined.您正在返回“allProfiles”,这是异步getAllBusinessProfiles()的结果,该结果要么返回未定义、错误,要么返回的 object 的字段之一未定义。 "error" object is not serializable in javascript “错误” object 在 javascript 中不可序列化

I had this issue using Mongoose and Next.js.我在使用 Mongoose 和 Next.js 时遇到了这个问题。

To solve it: I switched from convert require to import then wrapped my result in JSON.parse(JSON.stringify(result));为了解决这个问题:我从 convert require 切换到 import 然后将我的结果包装在JSON.parse(JSON.stringify(result)); . .

Good: import mongoose from 'mongoose';好: import mongoose from 'mongoose';

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

I had the same serialization error when accessing a Vercel system environment variable in getStaticProps .getStaticProps访问 Vercel 系统环境变量时,我遇到了相同的序列化错误。

Using JSON.stringify did not do the trick, but String() worked.使用JSON.stringify没有成功,但String()有效。 My code:我的代码:

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

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

Thanks to this GitHub issue for the inspiration感谢此 GitHub 问题的启发

Instead of using undefined , you have to use null as the value for your variables.而不是使用undefined ,您必须使用null作为变量的值。

Note that the error shows you exactly which variable is using undefined as its value.请注意,该错误会准确显示哪个变量使用undefined作为其值。 Just modify its value to be null .只需将其值修改为null

The value 'undefined' denotes that a variable has been declared, but hasn't been assigned any value.值“未定义”表示已声明变量,但尚未分配任何值。 So, the value of the variable is 'undefined'.因此,变量的值是“未定义”。 On the other hand, 'null' refers to a non-existent object, which basically means 'empty' or 'nothing'.另一方面,'null' 是指不存在的 object,基本上意味着'空'或'无'。

Source: [1]资料来源: [1]

try this, it worked for me:试试这个,它对我有用:

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,
    },
  };
}

I was having the same issue while trying to find a match in the array of data using the id.我在尝试使用 id 在数据数组中查找匹配项时遇到了同样的问题。 The issue i had was the items in the array had ids which were numbers while the value i was getting from params was a string.我遇到的问题是数组中的项目的 id 是数字,而我从 params 获得的值是一个字符串。 So all i did was convert the number id to a string to match the comparision.所以我所做的就是将数字 id 转换为字符串以匹配比较。

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

In getStaticProps() function, after fetching your data it will be in json format initially, but you should change it as follow:在 getStaticProps() function 中,在获取您的数据后,它最初将采用 json 格式,但您应该将其更改如下:

     const res = await fetch(`${APP_URL}/api/projects`);
     const data = JSON.parse(res);

now it will work.现在它可以工作了。

install a package called babel-plugin-superjson-next and superjson and added a .babelrc file with these contents:安装一个名为babel-plugin-superjson-nextsuperjson的 package 并添加一个包含以下内容的.babelrc文件:

 { "presets": ["next/babel"], "plugins": ["superjson-next"] }

see this topic: https://github.com/vercel/next.js/discussions/11498 .看到这个话题: https://github.com/vercel/next.js/discussions/11498

I had a similar problem too where I was fetching data through apollo directly inside of getStaticProps.我也有类似的问题,我直接在 getStaticProps 内部通过apollo获取数据。 All I had to do to fix the error was add the spread syntax to the return.我所要做的就是修复这个错误,将扩展语法添加到返回中。

    return {
    props: {
      data: { ...data }
    }
  }
return { props: { allProfiles: allProfiles || null } }

When you call api you should use try catch.当您调用 api 时,您应该使用 try catch。 It will resolve error.它将解决错误。

Example:例子:

import axios from "axios";
    export const getStaticProps = async () => {
        try {
            const response = await axios.get("http:...");
            const data = response.data;
            return {
                props: {
                    posts: data
                }
            }
        } catch (error) {
            console.log(error);
        }
    }

Hope help for you !希望对你有所帮助!

put res from API in Curly Brackets将 API 中的 res 放在花括号中

const { res }  = await axios.post("http://localhost:3000/api", {data})
return { props: { res } }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM