【问题标题】:FetchError: invalid json response body reason: Unexpected token < in JSON at position 0 - nextjsFetchError:无效的 json 响应正文原因:意外的令牌 < 在 JSON 中的位置 0 - nextjs
【发布时间】:2021-05-31 16:23:15
【问题描述】:

我正在使用 getStaticPropsgetStaticPaths,我使用 fetch API 来调用 API 端点(在我的例子中是 Wordpress 无头 CMS)并设置动态路由的路径。当我运行npm dev 时,它工作正常,数据被正确获取。但是在构建时它会给出错误:

FetchError:https://abr.af/wp/wp-json/wp/v2/advisors 处的无效 json 响应正文原因:意外的令牌

我的代码在pages/advisor/[advisor].js

export const getStaticPaths = async () => {
  const advisors = await getAdvisors()
  const paths = advisors.map((each) => {
    return {
      params: { advisor: each.slug },
    }
  })

  return {
    paths,
    fallback: false,
  }
}

export const getStaticProps = async ({ params }) => {
  const query = params.advisor
  const advisors = await getAdvisors()
  const advisor = advisors.find((advisor) => advisor.slug === query)
  return {
    props: {
      advisor,
    },
  }
}

我在component/FetchData.js中的获取函数

export async function getAdvisors() {
  const res = await fetch('https://abr.af/wp/wp-json/wp/v2/advisors', {
    method: 'GET',
    headers: {
      // update with your user-agent
      'User-Agent': '*',
      Accept: 'application/json; charset=UTF-8',
    },
  })
  const advisors = await res.json()

  return advisors
}

export async function getExpertise() {
  const res = await fetch('https://abr.af/wp/wp-json/wp/v2/expertise', {
    method: 'GET',
    headers: {
      // update with your user-agent
      'User-Agent': '*',
      Accept: 'application/json; charset=UTF-8',
    },
  })
  const expertise = await res.json()

  return expertise
}

我用谷歌搜索了这个问题,发现我应该在我的请求中添加 User-Agent 标头,但这不能解决我的问题。

我是 Next.js 的新手,我不知道任何帮助的原因是什么。

【问题讨论】:

    标签: wordpress next.js


    【解决方案1】:

    我遇到了同样的错误,不得不切换到getServerSideProps。就我而言,我使用的 api 是下一个在构建期间不容易获得的 api(数据库连接 + 获取)。

    我不得不回到NextJS documentation,以了解何时应该使用getStaticProps

    这就是所说的:

    • 渲染页面所需的数据在构建时可用 用户的请求。
    • 数据来自无头 CMS。
    • 数据可以 被公开缓存(不是特定于用户的)。
    • 必须预先呈现页面 (对于 SEO)并且速度非常快 — getStaticProps 生成 HTML 和 JSON 文件,这两个文件都可以由 CDN 缓存以提高性能。

    【讨论】:

    • 我全新安装了 WordPress,现在它可以工作了。
    猜你喜欢
    • 2021-10-14
    • 2022-10-24
    • 2016-12-13
    • 1970-01-01
    • 1970-01-01
    • 2020-02-05
    • 2021-09-12
    • 2018-10-17
    相关资源
    最近更新 更多