"TypeError: response.json is not a function" when trying to parse json

"TypeError: response.json is not a function" when trying to parse json

我收到一个我不明白的错误。我正在获取 json 格式的 API url,然后是 json 到 JS 对象解析,使用 json()

const response = fetch('https://power.larc.nasa.gov/api/temporal/monthly/point?parameters=ALLSKY_SFC_SW_DNI&community=RE&longitude=48.0000&latitude=27.0000&format=JSON&start=2001&end=2020');

const data = response.json();

谁能解释一下这个错误..

fetch是一个异步函数;它不会立即 return 响应(而是 Promise)。

如果要获取数据,需要在 Promise 中使用 fetch 调用中的 await (if the fetch is called inside another async function), or provide a callback via then method

fetch('https://power.larc.nasa.gov/api/temporal/monthly/point?parameters=ALLSKY_SFC_SW_DNI&community=RE&longitude=48.0000&latitude=27.0000&format=JSON&start=2001&end=2020')
.then(response => {
   const data = response.json();
});

处理来自响应的数据

如果你这样做是行不通的:

let data;

fetch('https://power.larc.nasa.gov/api/temporal/monthly/point?parameters=ALLSKY_SFC_SW_DNI&community=RE&longitude=48.0000&latitude=27.0000&format=JSON&start=2001&end=2020')
.then(response => {
   data = response.json();
});

console.log(data);

原因是因为 then 方法 中的回调是在响应 returned 之后执行的(例如这可能需要几秒钟) ,但是 console.log(data)fetch 被调用后立即执行 。这意味着数据尚未分配,可能 undefined。出于这个原因,如果你想把 data 放在某个地方,你需要 把你的代码放在回调中 .

function processData(responseData) {
    // Here, you can put your code to process the data from response
    console.log(responseData);
}

fetch('https://power.larc.nasa.gov/api/temporal/monthly/point?parameters=ALLSKY_SFC_SW_DNI&community=RE&longitude=48.0000&latitude=27.0000&format=JSON&start=2001&end=2020')
.then(response => {
    const data = response.json();

    processData(data);
});

这样 data 将在 获取后 被处理。

获取 returns 承诺,因为您正在向 API 发送请求。这种类型的函数是 asynchronous,因为我们不知道何时从 API.

返回响应

您可以在收到响应后使用 async/await or .then() and .catch() 来执行您的代码。

试试这个:

let returnedData;
fetch('https://power.larc.nasa.gov/api/temporal/monthly/point?parameters=ALLSKY_SFC_SW_DNI&community=RE&longitude=48.0000&latitude=27.0000&format=JSON&start=2001&end=2020')
.then((data) => {
    console.log(data)
    returnedData = data
})
.catch((error) => {
    console.log(error)
})