[英]"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.