簡體   English   中英

嘗試解析 json 時出現“TypeError:response.json 不是函數”

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

我收到一個我不明白的錯誤。 I'm fetching an API url in json format, followed by a json to JS object parsing, using 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是一個異步 function 它不會立即返回響應(您會得到Promise )。

如果要獲取數據,則需要使用await (如果在另一個async function中調用 fetch ),或者通過fetch調用中的Promise中的then方法提供回調

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方法中的回調是在響應返回后執行的(例如,這可能需要幾秒鍾),但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將在獲取進行處理。

Fetch 返回 Promise,因為您正在向 API 發送請求。 這種類型的函數是asynchronous的,因為我們不知道何時從 API 獲得響應。

當您收到響應時,您可以使用async/await.then() 和 .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)
})

暫無
暫無

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

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