[英]In Next.js, Error serializing getStaticProps?
I'm getting the following error in my Next.js app:我的 Next.js 应用程序中出现以下错误:
Error: Error serializing `.posts[0]` returned from `getStaticProps` in "/blog". Reason: `object` ("[object Promise]") cannot be serialized as JSON. Please only return JSON serializable data types.
I know there must be an issue resolving my promises somewhere, but I'm lost.我知道在某处解决我的承诺一定有问题,但我迷路了。 Please help!
请帮忙!
index.js
source code index.js
源代码
export async function getStaticProps() {
const posts = await getSortedPosts()
return { props: { posts } }
}
posts.js
source code posts.js
源代码
export async function getSortedPosts() {
const fileNames = readdirSync(POSTS_DIR)
const allPostsData = fileNames.map(fileName => {
const slug = fileName.replace(/\.md$/, '')
return getPost(slug)
});
await Promise.all(allPostsData);
return allPostsData.sort((a, b) => (a.date < b.date ? 1 : -1))
}
export async function getPost(slug) {
const fullPath = path.join(POSTS_DIR, `${slug}.md`)
const fileContents = readFileSync(fullPath, 'utf8')
const { content, data: meta } = parseYaml(fileContents)
const contentHtml = await markdownToHtml(content)
return {
slug,
contentHtml,
...meta,
}
}
async function markdownToHtml(md) {
const processedContent = await remark()
.use(remarkHtml)
.process(md)
return processedContent.toString()
}
I was able to resolve the promise chain by assigning the result of Promise.all
and passing it along.通过分配
Promise.all
的结果并将其传递,我能够解决 promise 链。
const promises = fileNames.splice(0, 2).map(fileName => {
const slug = fileName.replace(/\.md$/, '')
return getPost(slug)
});
const allPostsData = await Promise.all(promises); // Assign result of promise chain
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.