【发布时间】:2021-08-18 20:40:59
【问题描述】:
我正在开发一个基于天气的 API 项目以提高我的技能,但在获取数据时出现错误:
Uncaught (in promise) TypeError: result.main is undefined
这是负责从 API 获取数据的函数:
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 令牌密钥,所以这不是问题
【问题讨论】:
-
当你
console.log(result);,你看到{ main: ..., ... }了吗? (该错误是由于您尝试访问result.main.temp而result.main未定义) -
@ChrisG 是的,当我
console.log(result);它记录一个包含{main: {temp:...}}的对象(使用result.json()之后) -
console.log(result)的确切输出是什么? -
1.我一直无法重现这一点。不可能得到这个输出并且仍然得到你提到的错误。 2.我唯一能够重现此错误的情况是 API 调用本身返回 401(而不是您提到的输出)
-
这里的正确答案类似于
if (result.main) { ... },即在尝试访问其属性之前检查对象是否存在)。真的没有必要在这里发布答案;这不会帮助其他任何人。这是一个非常基本的错误,特定于您在其他地方调用该函数的方式。
标签: javascript api promise fetch