[英]Uncaught (in promise) TypeError: result.main is undefined
我正在研究基於天氣的 API 項目以提高我的技能,但是在獲取數據時出現錯誤:
Uncaught (in promise) TypeError: result.main is undefined
這里是負責從 API 中獲取數據的 function:
async function fetchData(cityName) {
const API_KEY = 'MY_API_TOKEN';
const fetchRes = {
method: 'GET',
redirect: 'manual',
mode: 'cors',
};
const response = await fetch(
`https://api.openweathermap.org/data/2.5/weather?q=${cityName}&appid=${API_KEY}`,
fetchRes
);
const result = await response.json();
const data = result.main.temp;
console.log(data);
}
使用此調用修復
fetchData("london");
在這里,我正在使用另一個輸入和搜索按鈕獲取城市名稱
注意:出於安全原因,我隱藏了我的 API 令牌密鑰,所以這不是問題
單獨的效果
return
結果而不是記錄它 -
async function fetchData(cityName) {
const API_KEY = 'MY_API_TOKEN';
const fetchRes = {
method: 'GET',
redirect: 'manual',
mode: 'cors',
};
const response = await fetch(
`https://api.openweathermap.org/data/2.5/weather?q=${cityName}&appid=${API_KEY}`,
fetchRes
);
const result = await response.json();
return result.main.temp // <-- return the result
}
現在附加效果和錯誤處理程序 -
fetchData(...)
.then(console.log) // <- receives data
.catch(console.error) // <- receives error
您可以在單個.then
中附加效果和錯誤處理程序 -
fetchData(...)
.then(console.log, console.error) // <- same behaviour as above
單獨的關注點
我建議分離關注點,以便更輕松地讀取/寫入您的函數 -
const getJSON = (url, opts = {}) =>
fetch(url, opts).then(r => r.json())
現在您不必每次想查詢一些 JSON 時都重復自己 -
async function fetchData(cityName) {
const API_KEY = 'MY_API_TOKEN';
const url = `https://api.openweathermap.org/data/2.5/weather?q=${cityName}&appid=${API_KEY}`
const opts = {
method: 'GET',
redirect: 'manual',
mode: 'cors',
};
const result = await getJSON(url, opts) // <- reusable function
return result.main.temp
}
URL處理
我建議不要使用字符串構建 URL。 而是使用 URL searchParams API 以編程方式構建事物 -
async function fetchData(cityName) {
const API_KEY = 'MY_API_TOKEN'
// use URL api
const u = new URL("https://api.openweathermap.org/data/2.5/weather")
u.searchParams.set("q", cityName)
u.searchParams.set("appid", API_KEY)
const opts = {...}
const result = await getJSON(u, opts) // <- pass URL object
return result.main.temp
}
如您所見,每次需要設置/修改一些 URL 參數時都必須編寫所有這些內容會很煩人。 應用上面的教訓,我們寫href
-
function href(url, params = {}) {
const u = new URL(u)
for (const [key, value] of Object.entries(params))
u.searchParams.set(key, value)
return u.toString()
}
現在您可以避免在常用函數中重復和容易出錯的代碼 -
async function fetchData(cityName) {
const API_KEY = 'MY_API_TOKEN'
// use our href helper
const u = href("https://api.openweathermap.org/data/2.5/weather", {
q: cityName,
appid: API_KEY
})
// use getJSON helper
const result = await getJSON(u, {...})
return result.main.temp
}
fetchData("someCity").then(console.log, console.error)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.