错误:如何从 getStaticProps 序列化数据:Next.js [英] Error: How to serialize data from getStaticProps : Next.js
问题描述
我正在使用 Next.js,我尝试访问数据但收到此错误:
错误:序列化从/profile/[slug]"中的getStaticProps"返回的.profileData"时出错.原因:`undefined` 无法序列化为 JSON.请使用 `null` 或省略此值.
我的代码:
import { getAllBusinessProfiles } from '../../lib/api';const Profile = ({ allProfiles: { edges } }) =>{返回 (<><头><title>简介</title></头><英雄/><部分>{edges.map(({ 节点}) => (<div key={node.id}><链接 href={`/profile/${node.slug}`}><a>{node.businessInfo.name} </a></链接></div>))}</部分></>);}导出默认配置文件;导出异步函数 getStaticProps() {常量 allProfiles = 等待 getAllBusinessProfiles();返回 {道具: {所有配置文件}};}
从 api.js 获取所有业务配置文件:
const API_URL = process.env.WP_API_URL;异步函数 fetchAPI(query, { variables } = {}) {const headers = { 'Content-Type': 'application/json' };const res = await fetch(API_URL, {方法:'POST',标头,正文: JSON.stringify({ 查询,变量 })});常量 json = 等待 res.json();如果(json.errors){控制台.log(json.errors);console.log('错误详情', 查询, 变量);throw new Error('获取 API 失败');}返回 json.data;}导出异步函数 getAllBusinessProfiles() {常量数据 = 等待 fetchAPI(`查询所有配置文件 {businessProfiles(其中:{orderby:{field:DATE,order:ASC}}){边{节点{日期标题蛞蝓关联乌里业务信息 {名称标题公司图片 {媒体项目网址替代文本}强调电话城市国家FacebookInstagram电子邮件网站个人资料 {轮廓个人资料信息}扩展配置文件 {标题信息}}}}}}`);返回数据?.businessProfiles;};
这可能是什么错误?我在 Next.js 上使用了 getStaticProps 方法,但得到了上面的错误.请检查.谢谢.
错误:服务器错误错误:序列化从/profile/[slug]"中的 getStaticProps
返回的 .profileData
时出错.原因:undefined
无法序列化为 JSON.请使用 null
或省略此值.
我不知道是什么原因造成的.
添加 JSON.stringify
调用返回对象的异步函数时.
尝试像这样修改您的 getStaticProps
函数.
导出异步函数 getStaticProps() {常量配置文件 = 等待 getAllBusinessProfiles();const allProfiles = JSON.stringify(profiles)返回 {道具: {所有配置文件}};}
<块引用>
JSON.stringify()
方法将 JavaScript 对象或值转换为 JSON 字符串,如果指定了替换函数,则可选地替换值,或者如果指定了替换器数组,则可选地仅包含指定的属性.
来源:MDN
I'm working with Next.js, I tried accessing data but got this error:
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:
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. Please, check. Thanks.
The error:
Server Error
Error: Error serializing .profileData
returned from getStaticProps
in "/profile/[slug]".
Reason: undefined
cannot be serialized as JSON. Please use null
or omit this value.
I don't know what could cause this though.
Add JSON.stringify
when calling an asynchronous function that returns an object.
Try modifying your getStaticProps
function like this.
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.
Source: MDN
这篇关于错误:如何从 getStaticProps 序列化数据:Next.js的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!