javascript - 当我尝试使用 json 获取 API 返回值时出错

标签 javascript json async-await

我的代码有一些问题。我正在使用开放天气 API 来创建此应用程序。我可以轻松获取weather.js 文件中的值并转移到 UI。只有它有一些值会在控制台中响应错误。遵循代码和错误。

文件weather.js

class Weather {
  constructor(city, state) {
    this.apiKey = "xxxxxxxxxxxx";
    this.city = city;
    this.state = state;
  }

  // Fetch weather from API
  async getWeather() {
    const response = await fetch(
      `https://api.openweathermap.org/data/2.5/weather?q=${this.city},${this.state}&APPID=${this.apiKey}`
    );

    const responseData = await response.json();

    return responseData;
  }

  // Change weather location
  changeLocation(city) {
    this.city = city;
    this.state = state;
  }
}

文件 ui.js

class UI {
  constructor() {
    this.location = document.getElementById("w-location");
    this.desc = document.getElementById("w-desc");
    this.string = document.getElementById("w-string");
    this.details = document.getElementById("w-details");
    this.icon = document.getElementById("w-icon");
    this.humidity = document.getElementById("w-humidity");
    this.feelsLike = document.getElementById("w-feels-like");
    this.dewpoint = document.getElementById("w-dewpoint");
    this.wind = document.getElementById("w-wind");
  }

  paint() {
    this.location.textContent = weather.name;
    this.desc.textContent = weather.weather[0].description;
  }
}

文件app.js

// Init Weather Class
const weather = new Weather("rio de janeiro");

const ui = new UI();

// Get weather on DOM load
document.addEventListener("DOMContentLoaded", getWeather);

//weather.changeLocation("los angeles");

function getWeather() {
  weather
    .getWeather()
    .then(results => {
      ui.paint();
    })
    .catch(err => console.log(err));
}

Console Error:

TypeError: Cannot read property '0' of undefined

at UI.paint (ui.js:16)

at app.js:15

如果我通过描述属性在weather.js 文件中进行console.log 调用,它会正确回答我,但是当我调用ui.js 时,它会给出此错误。

这不仅适用于该属性,也适用于其他属性,我尝试调用国家属性并说它尚未设置。怎么解决?有人可以帮助我吗?

最佳答案

您可以将 api 调用的结果作为参数传递给 paint方法,因为 Weather类没有 weather属性:

  paint(data) {
    this.location.textContent = data.name;
    this.desc.textContent = data.weather[0].description;
  }


function getWeather() {
  weather
    .getWeather()
    .then(results => {
      ui.paint(results);
    })
    .catch(err => console.log(err));
}

还要确保您的 api 响应实际上有 weather prop,它是一个数组。

关于javascript - 当我尝试使用 json 获取 API 返回值时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59039804/

相关文章:

php - 是否可以在没有 https 服务器的情况下拥有安全的 Web 表单?

javascript - 如何在 react 中悬停时在图像上添加过渡时间?

javascript - react : How to map select option value to a state key?

ios - swift: 将多个 <key, value> 对象添加到 NSDictionary

asp.net-mvc - 从 Session_Start 调用异步方法

javascript - 下载人物头像并在node.js中展示

json - Dart 通过 EndPoints 将 JSON 发布到 Google App Engine

json 格式化一行中的每个对象

.net - IDisposable.Dispose() 未在异步方法的 Release模式下调用

c# - SignalR 连续消息传递