为什么我在JavaScript控制台中没有定义
我创建了一个类调用weather,它从一个API获取天气数据(我使用openWeather获取天气数据)。我还在另一个文件中创建了app.js方法,将天气数据输出到控制台 但是,当我运行程序时,它会在控制台(app.js)中给我一条错误消息,说未定义。 我正在使用javascript承诺和异步函数 请帮忙!谢谢为什么我在JavaScript控制台中没有定义,javascript,html,api,asynchronous,Javascript,Html,Api,Asynchronous,我创建了一个类调用weather,它从一个API获取天气数据(我使用openWeather获取天气数据)。我还在另一个文件中创建了app.js方法,将天气数据输出到控制台 但是,当我运行程序时,它会在控制台(app.js)中给我一条错误消息,说未定义。 我正在使用javascript承诺和异步函数 请帮忙!谢谢 //This is the weather class class Weather { constructor (city){ this.apiKey
//This is the weather class
class Weather {
constructor (city){
this.apiKey = '59fdf0cfa3f226ec087ef1dec6a1755a';
this.city = city
// this.state = state
}
//fetch weather from API
async getWeather(){
const response = await fetch (`https://samples.openweathermap.org/data/2.5/weather?
q=${this.city},uk&appid=${this.apiKey}.json`);
const responseData = await response.json();
return responseData.current_observation;
}
//Change weather location
changeLocation(city,state){
this.city = city;
this.state = state;
}
}
这是app.js方法
const weather = new Weather('london');
weather.getWeather()
.then(results => {
console.log(results); //this is where i get the undefined error message in the console.
})
.catch(err => console.log(err));
}
两个问题:
current\u observation
您希望获取的weather
或weather[0]
,因为此属性包含天气数据修复这两个问题应该可以阻止您在
控制台中获取未定义的日志
如果从API中检索数据,请尝试:。然后(结果=>{If(results){console.log(results);//这是我在控制台中获取未定义错误消息的地方。})该响应似乎没有当前\u观察
属性。您的代码中没有实际问题,只是您尝试访问的属性不存在。当我从代码中删除“current_observation”时,控制台中会出现此错误(错误:“404”)。在注释掉代码中的“current_observation”后,我将在控制台中获得(错误:“404”)
@CHBCHB55好吧,请求的任何部分都没有改变,你确定你的API请求一直在工作吗?API请求对我来说也很好,我不知道404可能来自哪里。非常感谢@chbch55,它现在工作了,我的问题是模板文本,当我转到下一行时。再次感谢!