【问题标题】:NextJS: TypeError: Cannot read property 'json' of undefinedNextJS:TypeError:无法读取未定义的属性“json”
【发布时间】:2020-12-28 05:24:36
【问题描述】:

我已将此代码放入 NextJS 环境中的 pages 文件夹中。它获取调用外部 API Rest 的数据,并且它正在工作,因为 console.log(response); 行通过控制台向我显示 Json API 响应。我遇到的问题是我在浏览器中收到此错误:

TypeError:无法读取未定义的属性“json”

对应这行代码:

const data = await res.json();

这是包含代码的完整文件:

import React from "react";
import fetch from "node-fetch";

const getFetch = async (invoicesUrl, params) => {
  fetch(invoicesUrl, params)
    .then((response) => {
      return response.json();
    })
    .then((response) => {
      console.log(response);
    })
    .catch((err) => {
      console.log(err);
    });
};

export const getServerSideProps = async () => {
  const invoicesUrl = "https://192.168.1.38/accounts/123456";
  const params = {
    method: "get",
    headers: {
      Accept: "application/json",
      "Content-Type": "application/json",
    },
  };
  const res = await getFetch(invoicesUrl, params);
  const data = await res.json();
  console.log("Data Json: ", data);

  return { props: { data } };
};

这是我通过控制台看到的 Json API 响应:

{
  account: [
    {
      id: '7051321',
      type: 'probe',
      status: 'open',
      newAccount: [Object],
      lastDate: '2020-07-04',
      taxExcluded: [Object],
      totalRecover: [Object],
      documentLinks: []
    },
  ]
}

知道如何解决吗? 提前致谢。

更新 这里的代码运行良好:

import React from "react";
import fetch from "node-fetch";

const getFetch = async (invoicesUrl, params) => {
   return fetch(invoicesUrl, params);
};

export const getServerSideProps = async () => {
  const invoicesUrl = "https://192.168.1.38/accounts/123456";
  const params = {
    method: "get",
    headers: {
      Accept: "application/json",
      "Content-Type": "application/json",
    },
  };
  try {
    const res = await getFetch(invoicesUrl, params);
    const data = await res.json();
    console.log("Data JSON: ", data);
    return { props: { data } };
  } catch (error) {
    console.log("Data ERROR: ", error);
  }
};

【问题讨论】:

    标签: javascript json reactjs next.js


    【解决方案1】:

    有几件事你必须改变。

    const getFetch = async (invoicesUrl, params) => {
      fetch(invoicesUrl, params)
        .then((response) => {
          return response.json();
        })
        .then((response) => {
          console.log(response);
          return response; // 1. Add this line. You need to return the response.
        })
        .catch((err) => {
          console.log(err);
        });
    };
    
    export const getServerSideProps = async () => {
      const invoicesUrl = "https://192.168.1.38/accounts/123456";
      const params = {
        method: "get",
        headers: {
          Accept: "application/json",
          "Content-Type": "application/json",
        },
      };
      const data = await getFetch(invoicesUrl, params);
      // const data = await res.json(); 2. Remove this you have already converted to JSON by calling .json in getFetch
      console.log("Data Json: ", data); // Make sure this prints the data.
    
      return { props: { data } };
    };
    
    

    【讨论】:

    • 我已经按照您的建议进行了更改,现在我收到此错误:“SerializableError: Error serializing .data returned from getServerSideProps in "/invoicing/invoices"。原因:undefined无法序列化为 JSON。请使用null 或一起省略此值”。您的 getFetch 函数中有两个“返回”,对吗?
    • 原因是你的API返回的响应是不可序列化的。如果您使用完整对象更新您的问题,我将能够指出问题所在。如果没有,您可以使用此处的答案自行查找:stackoverflow.com/questions/30579940/…
    • 好的,可能无法序列化的原因是那些在控制台中具有内容“[Object]”的元素,但如果我以另一种方式(curl,Postman)调用 API 则具有内容。
    • 是的,它是 [Object] 内部不可序列化的东西。对于 NextJS,它需要可序列化。您可以使用:stackoverflow.com/questions/41587443/… 打印整个结构并查看问题出在哪里。我很乐意提供更多帮助。顺便说一句,我想我已经解决了这个问题的原始问题。如果是这样,请接受..:)
    • 感谢您的帮助。我会看看那个链接。抱歉,但我不能接受您的答案是正确的(我不想混淆其他用户),因为尝试多次后它对我不起作用。我已经更新了我原来的问题,在更新标题之后,我输入了适合我的代码。但是,可能是其他有此问题的用户可以将您的答案投票为正确的!再次感谢。
    【解决方案2】:

    您的 return 语句在错误的位置。 当函数期望返回时。当语句不在 Promise then 函数内执行时,您需要返回,因为它是一个异步回调函数,与 getFetchfunction 内的语句不同步。我希望我已经把事情说清楚了。以下是返回内容的代码

    import React from "react";
    import fetch from "node-fetch";
    
    const getFetch = async (invoicesUrl, params) => {
      return fetch(invoicesUrl, params);
    };
    
    export const getServerSideProps = async () => {
      const invoicesUrl = "https://192.168.1.38/accounts/123456";
      const params = {
        method: "get",
        headers: {
          Accept: "application/json",
          "Content-Type": "application/json",
        },
      };
      try{
         const res = await getFetch(invoicesUrl, params);
         console.log("Data Json: ", res);
      }catch(error){
         console.log("Data Json: ", error);
      }
      return { props: { res } };
    };
    

    【讨论】:

    • 好的,谢谢!它帮助了我。现在我的代码正在运行。我将使用有效的代码更新我的原始问题。但是,我认为您应该将“return { props: { data } }”更改为“return { props: { res } }”。再次感谢。
    猜你喜欢
    • 2022-01-27
    • 1970-01-01
    • 1970-01-01
    • 2019-11-13
    • 2023-04-01
    • 2015-10-06
    • 2023-03-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多