簡體   English   中英

Next.js:FetchError: invalid json 響應正文 意外的令牌 < 在 JSON 在 Z4757FE07FD492A8BE0EA673A

[英]Next.js:FetchError: invalid json response body Unexpected token < in JSON at position 0

我正在嘗試使用getStaticProps來簡單地發出請求,然后將該數據從它傳遞給組件:

但我收到了這個錯誤:

FetchError: invalid json response body at https://www.ajmadison.com/product3.0/packages.index.json.php?sku=RF28R7351SR reason: Unexpected token < in JSON at position 0

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,
    },
  };
}

我試圖對其進行字符串化,但這沒有用:我也對評論感到困惑:

這個 function 在構建時在服務器端被調用。 它不會在客戶端調用,因此您甚至可以直接進行數據庫查詢。 請參閱“技術細節”部分。

然后如您所見,有一條評論指出:

調用外部 API 端點以獲取帖子。

但是在他們的文檔中有一個關於 API 路由的完整部分

任何人都可以幫助我這是怎么回事?

更新

Alexey 提供了一些深刻的見解,但就像我對他說的那樣,我在 axios 文檔中找不到更改用戶代理!

我認為您所指的端點出於某種原因對“用戶代理”敏感。

當我嘗試像這樣使用 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:嘗試將“用戶代理”header 添加到您的請求中。

阿列克謝讓我走上了正軌! 朋友,謝謝!

結束了你必須這樣做:

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

不要在api file中使用 res.status(200).json(data res.status(200).json(data) ,而是使用res.status(200).json(JSON.stringify(data)) 這將消除控制台中的 JSON 錯誤。 這對我有用。

對我來說,.json .json()調用了 HTTP 錯誤,在響應正文中返回 HTML

我認為數據不是從最后獲取的,這是為什么。 我遇到了同樣的問題我重新啟動了我的系統和網絡,它可以完美地恢復

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM