【发布时间】: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