javascript - 为什么我的控制台上未定义?
问题描述
我正在尝试使用 fetch 和 promise 进行 AJAX 调用。我想在控制台中显示城市。我能够显示温度,但由于某种原因,该位置显示为未定义。请指教。下面是我的代码:
function getWeather(woeid) {
// You wanna pass in the API URL into the fetch method as a string
// Moesif Orign & CORS chrome extension is used to fetch this API since we are practicing locally
fetch(`https://www.metaweather.com/api/location/${woeid}/`) // Automatically returns a promise
.then(result => { // The fetch AJAX request will be called result
console.log(result);
return result.json(); // This will process the data (body:ReadableSteam). Returns a promise
})
.then(data => {
//console.log(data);
const today = data.consolidated_weather[0];
console.log(`Todays temperatures in ${today.title} will stay between ${today.min_temp} and ${today.max_temp}.`);
})
.catch(error => console.log(error));
}
getWeather(2487956);
getWeather(44418);
解决方案
正如尼克所说,您似乎需要正确的数据选项。所以这段代码实际上修复了它:
const todaySrc = data.sources[0];
todaySrc.title // BBC
这是一个完整的片段:
function getWeather(woeid) {
// You wanna pass in the API URL into the fetch method as a string
// Moesif Orign & CORS chrome extension is used to fetch this API since we are practicing locally
fetch(`https://www.metaweather.com/api/location/${woeid}/`) // Automatically returns a promise
.then(result => { // The fetch AJAX request will be called result
console.log(result);
return result.json(); // This will process the data (body:ReadableSteam). Returns a promise
})
.then(data => {
//console.log(data);
const today = data.consolidated_weather[0];
const todaySrc = data.sources[0];
console.log(`Todays temperatures in ${todaySrc.title} will stay between ${today.min_temp} and ${today.max_temp}.`);
})
.catch(error => console.log(error));
}
getWeather(2487956);
getWeather(44418);
推荐阅读
- java - 应用程序登录,但重定向回登录
- java - 将 JHipster 项目部署到 tomcat
- c# - 将 Outlook 邮件和附件转换为 PDF 的最佳方法(最好将它们合并)?
- php - 重力形式 (AJAX) 响应出现在 iframe 中
- hibernate - Hibernate - 在一个查询中初始化多个集合
- reactjs - ThemeProvider 不会将主题应用于材质 ui 库中的子组件
- rust - 我如何才能限定或保持更高的优先级,而不是由特征提供的方法?
- postgresql - 如何在 yii2 updateAll() 中使用替换查询?
- python - numpy.add 如何转化为 numpy.ufunc
- grep - 在多个文件中匹配多个单词的 grep