为什么我在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

我创建了一个类调用weather,它从一个API获取天气数据(我使用openWeather获取天气数据)。我还在另一个文件中创建了app.js方法,将天气数据输出到控制台

但是,当我运行程序时,它会在控制台(app.js)中给我一条错误消息,说未定义。 我正在使用javascript承诺和异步函数

请帮忙!谢谢

//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));
}
两个问题:
  • 复制和粘贴时,您的查询在问号后面和字母“q”之前有一堆额外的空格,不知道您是否也是这样运行代码的。如果您使用的是模板文本、反勾号`,并且要移到下一行,这将是一个问题
  • 您不希望获取不存在的属性
    current\u observation
    您希望获取的
    weather
    weather[0]
    ,因为此属性包含天气数据

  • 修复这两个问题应该可以阻止您在
    控制台中获取
    未定义的
    日志

    如果从API中检索数据,请尝试:。然后(结果=>{If(results){console.log(results);//这是我在控制台中获取未定义错误消息的地方。})该响应似乎没有
    当前\u观察
    属性。您的代码中没有实际问题,只是您尝试访问的属性不存在。当我从代码中删除“current_observation”时,控制台中会出现此错误(错误:“404”)。在注释掉代码中的“current_observation”后,我将在控制台中获得
    (错误:“404”)
    @CHBCHB55好吧,请求的任何部分都没有改变,你确定你的API请求一直在工作吗?API请求对我来说也很好,我不知道404可能来自哪里。非常感谢@chbch55,它现在工作了,我的问题是模板文本,当我转到下一行时。再次感谢!