簡體   English   中英

object`(“[object Response]”)不能序列化為 JSON?

[英]object` (“[object Response]”) cannot be serialized as JSON?

我正在嘗試通過代碼消耗我的 api 我收到此錯誤

object` ("[object Response]") 不能序列化為 JSON

但是當我通過瀏覽器調用或使用這個 api 時,我得到了響應。

這是我的代碼https://codesandbox.io/s/naughty-platform-1xket?file=/pages/index.js

我正在像這樣消耗我的 api

 console.log("-----");
  const cc = await fetch("https://1xket.sse.codesandbox.io/api/basecss/");
  console.log(cc, "llll");

API 設計

export default async (req, res) => {
  const stylesheet = await (
    await fetch("https://www.****.com/asset/web/css/***-base.css", {})
  ).text();
  console.log(stylesheet, "server");
  res.status(200).send(stylesheet);
};

我在服務器上得到這個控制台值。 但是當我通過代碼調用這個 api 時,我收到了這個錯誤

object` ("[object Response]") cannot be serialized as JSON. Please only return JSON serializable data types

那是因為fetch返回一個Response ,返回響應后,需要解析響應response.json() response.text()等。這也是異步操作,相信不能嵌套await語句像那樣。

  const response = await fetch("https://www.****.com/asset/web/css/***-base.css")
  const data = await response.text()

您收到該錯誤是因為您在getStaticProps中返回了不可序列化的響應 object ( cc )。 getStaticPropsgetServerSideProps只允許從它們返回可序列化的內容

要解決此問題,您首先需要將響應數據轉換為文本,然后才能返回它。 您還需要更改您的道具以匹配IndexPage組件中預期的道具。

// pages/index.js

export async function getStaticProps() {
    const res = await fetch("https://1xket.sse.codesandbox.io/api/basecss/");
    const stylesheet = await res.text(); // Converts response data to text

    return {
        props: {
            stylesheet // Changes prop name from `cc` to `stylesheet` to match component
        }
    };
}

我為 Firestore 類型(特別是地理點和時間戳類型)解決此問題的方法是使用某種方法將不可序列化的屬性轉換為一個。

 CreatedAt: data.createdAt.toMillis(), updatedAt: data.updatedAt.toMillis(), coordinates: null, latitude: Number(JSON.stringify(data?.coordinates?.latitude) ), longitude: Number(JSON.stringify(data?.coordinates?.longitude)),

對於 Firestore 時間戳對象,您可以使用 .toMillis() 方法。 對於 Firestore Geopoint 對象,您可以先將位置(坐標)轉換為“null”,然后如果您需要特定的緯度和經度屬性,您可以使用緯度和經度屬性將它們拉出,然后將它們轉換為“數字” ”。

暫無
暫無

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

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