【问题标题】:Next.js:FetchError: invalid json response body Unexpected token < in JSON at position 0Next.js:FetchError: invalid json response body Unexpected token < in JSON at position 0
【发布时间】:2020-11-07 15:04:59
【问题描述】:

我正在尝试使用getStaticProps 来简单地发出请求,然后将该数据从它传递给组件:

但我收到此错误:

FetchError: 无效的 json 响应正文 https://www.ajmadison.com/product3.0/packages.index.json.php?sku=RF28R7351SR 原因:意外的令牌

import AppliancePackage from '../components/AppliancePackage.jsx';

function HomePage({ data }) {
  return (
    <>
      <AppliancePackage appliances={data} />
    </>
  );
}

export default HomePage;

// This function gets called at build time on server-side.
// It won't be called on client-side, so you can even do
// direct database queries. See the "Technical details" section.

export async function getStaticProps() {
  // Call an external API endpoint to get data.
  // You can use any data fetching library

  var res = await fetch(
    'https://www.ajmadison.com/product3.0/packages.index.json.php?sku=RF28R7351SR'
  );

   var json = await res.json();

   data = JSON.stringify(json);
   console.log('data ', data);

  return {
    props: {
      data: json,
    },
  };
}

我尝试对其进行字符串化,但没有成功!我也有点被 cmets 搞糊涂了:

此函数在构建时在服务器端调用。 它不会在客户端被调用,所以你甚至可以这样做 直接数据库查询。请参阅“技术细节”部分。

然后如您所见,有一条评论指出:

调用外部 API 端点以获取帖子。

但在他们的docs 中有一个关于 API 路由的完整部分

谁能帮我看看怎么回事?

更新

Alexey 贡献了一些深刻的见解,但就像我对他说的那样,我在 axios 文档中找不到更改用户代理的方法!

【问题讨论】:

    标签: javascript node.js reactjs next.js getstaticprops


    【解决方案1】:

    我认为您所指的端点出于某种原因对“用户代理”敏感。

    当我尝试像这样使用 CURL 获取它时,它返回了一些 HTML 响应(这当然不是有效的 JSON)

    curl https://www.ajmadison.com/product3.0/packages.index.json.php?sku=RF28R7351SR
    

    但这样它确实可以工作并返回 JSON,就像通过浏览器访问一样:

    curl -H "User-Agent: some browser" https://www.ajmadison.com/product3.0/packages.index.json.php?sku=RF28R7351SR  
    

    TLDR:尝试在您的请求中添加“user-agent”标头。

    【讨论】:

    【解决方案2】:

    Alexey 让我走上了正轨!谢谢我的朋友!

    你必须这样做:

    export async function getStaticProps() {
      // Call an external API endpoint to get posts.
      // You can use any data fetching library
    
      var res = await axios.get(
        'https://www.ajmadison.com/product3.0/packages.index.json.php?sku=RF28R7351SR',
        {
          headers: {
            Accept: 'application/json, text/plain, */*',
            'User-Agent': '*',
          },
        }
      );
      var res = JSON.stringify(res.data);
      console.log('res ', res);
    
      // By returning { props: posts }, the Blog component
      // will receive `posts` as a prop at build time
      return {
        props: {
          data: res,
        },
      };
    }
    

    正在添加标题:

      headers: {
        Accept: 'application/json, text/plain, */*',
        'User-Agent': '*',
      },
    

    对于任何User-Agent*

    【讨论】:

      【解决方案3】:

      不要在api file 中使用res.status(200).json(data),而是使用res.status(200).json(JSON.stringify(data))。这将消除控制台中的 JSON 错误。这对我有用。

      【讨论】:

        【解决方案4】:

        对我来说,是 .json() 调用 HTTP 错误,在响应正文中返回 HTML

        【讨论】:

          【解决方案5】:

          NextJS 上使用 Apollo Client 时出现同样的错误:

          import { ApolloClient, InMemoryCache } from "@apollo/client";
          
          const client = new ApolloClient({
            uri: "https://example.com/graphql",
            cache: new InMemoryCache(),
          });
          

          所以,我在 uri 中的 url 末尾添加了一个斜杠“/”

          import { ApolloClient, InMemoryCache } from "@apollo/client";
          
          const client = new ApolloClient({
            uri: "https://example.com/graphql/", // Here
            cache: new InMemoryCache(),
          });
          

          终于解决了这个错误。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2021-09-30
            • 1970-01-01
            • 1970-01-01
            • 2017-12-15
            • 2022-01-04
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多