【问题标题】:object` ("[object Response]") cannot be serialized as JSON?object` ("[object Response]") 不能序列化为 JSON?
【发布时间】:2021-04-17 17:29:37
【问题描述】:

我正在尝试通过代码使用我的 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

【问题讨论】:

    标签: javascript node.js reactjs next.js


    【解决方案1】:

    那是因为fetch返回了一个Response,返回响应后需要解析响应response.json()response.text()等,这也是异步操作,相信你做不到嵌套await 这样的语句。

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

    【讨论】:

      【解决方案2】:

      您收到该错误是因为您在 getStaticProps 中返回了一个不可序列化的响应对象 (cc)。 getStaticProps and getServerSideProps only allow serializable content to be returned 来自他们。

      要解决此问题,您首先需要将响应数据转换为文本,然后才能返回。您还需要更改您的 props 以匹配 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
              }
          };
      }
      

      【讨论】:

        【解决方案3】:

        我为 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”,然后如果您需要特定的纬度和经度属性,您可以使用纬度和经度属性将它们拉出,然后将它们转换为“数字” ”。

        【讨论】:

          猜你喜欢
          • 2021-06-15
          • 2020-04-02
          • 2021-06-14
          • 2016-08-02
          • 1970-01-01
          • 1970-01-01
          • 2021-04-14
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多