ash*_*y g 2 javascript http fetch reactjs
完整错误:
错误:
.b从getStaticProps“/”中返回的序列化错误。原因:(object"[object Promise]") 无法序列化为 JSON。请仅返回 JSON 可序列化数据类型。
我正在尝试调用我的函数之一,该函数从 API 端点检索一些数据,但是当尝试将此数据传递给 props 时,我收到错误。我不太确定我做错了什么,因为如果 fetch 调用在 GetStaticProps 内,则它会起作用,但我希望 fetch 调用的所有逻辑都存在于单独的 js 页面中以减少冗余,但是这样做时会创建此错误。
export async function getStaticProps() {
let b = WordpressService.getPageByIdTest(50);
return {
props: {
b: b,
},
revalidate: 30
}
Run Code Online (Sandbox Code Playgroud)
}
const WordpressService = {
async getPageByIdTest(id) {
const resIndexPage = await fetch(`${url}pages/${id}`);
const indexPageData = await resIndexPage.json();
return indexPageData;
}
}
Run Code Online (Sandbox Code Playgroud)
我正在查看最新版本的 nextjs,当我运行它时,我确实注意到该演示很奇怪。具体来说,我在运行他们的示例时遇到此错误:
错误:从 中返回了附加密钥
getStaticProps。适用于您的组件的属性必须嵌套在该props键下,例如
export async function getSortedPostsData() {
// Instead of the file system,
// fetch post data from an external API endpoint
const res = await fetch('..')
return res.json()
}
Run Code Online (Sandbox Code Playgroud)
这不完全是您的问题,但通过 res.json() 分配 props 对象也会导致您遇到的相同错误。
因此,对我来说,使用节点 15,我将 api 调用更改为:
export async function getStaticProps() {
const url = `https://my-url`
const result = await fetch(url)
return { props: {
result: await result.json()
}}
}
Run Code Online (Sandbox Code Playgroud)
这解决了我的问题。所以 Ivar 的评论看起来是正确的 - 等待结果,然后在我的例子中,我还必须等待来自 node-fetch 的 json 结果,以便正确完成承诺。
| 归档时间: |
|
| 查看次数: |
11045 次 |
| 最近记录: |