【问题标题】:res.json is not a function - Next.jsres.json 不是一个函数 - Next.js
【发布时间】:2021-01-18 15:20:29
【问题描述】:

Next.js 文档有些模棱两可,对我的问题没有帮助——我在使用 getStaticPaths 函数时遇到了问题。以下是我的代码:

export async function getStaticPaths() {
    
    let res =  fetch("localhost:3000/api/main")
    const paths = res.json().map(state => ({
      params: {id: states.id},
    }))

    return {paths,
      fallback: false}
  }

对于为什么这不起作用有什么想法吗?我还有一个 getStaticProps 函数,它可以正确加载 res.json()

【问题讨论】:

  • 嘿,也放 http:http://localhost:3000/api/main,你应该等待获取:const res = await fetch(url)
  • fetch 返回一个未决的承诺,它没有json() 方法,所以res.json() is *clearly* not a function。见上面哈迪的回答。

标签: javascript next.js


【解决方案1】:

你应该这样做:

  export async function getStaticPaths() {
    const res =  await fetch("http://localhost:3000/api/main")
    const decoded = await res.json();
    const paths = decoded.map(state => ({
      params: {state: states.id},
    }));
    return {
      paths,
      fallback: false
    }
  }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-03-19
    • 2018-07-05
    • 2019-01-11
    • 1970-01-01
    • 1970-01-01
    • 2017-06-23
    • 1970-01-01
    相关资源
    最近更新 更多