currentArray.forEach不是函数(提取API)

时间:2018-07-16 02:12:26

标签: javascript ajax xmlhttprequest fetch

我正在尝试查询URL字符串并提取一些天气数据。我得到响应,但是由于某种原因,我无法提取数据。我收到一条错误消息说

const weatherForm = document.querySelector("#weather-form");
weatherForm.addEventListener("submit", fetchWeather);

function fetchWeather(e) {
  e.preventDefault();
  
  const searchTerm = document.querySelector(".search").value;
  fetch(`https://api.apixu.com/v1/current.json?key=c54944da22b147b48ec152033160205&q=${searchTerm}`)
  .then((response) => {return response.json(); })
  .then((resp => {
   // console.log(resp);
    let currentArray = resp.current;
    console.log(currentArray);
    showWeather(currentArray);
  }))
  .catch(err => console.log(err));
}

function showWeather(currentArray) {
  alert("Hello");
  const results = document.querySelector(".results");
  
  let output = '<div class="container">';
  currentArray.forEach((weatherData => {
    output += `
    <h2>${weatherData.feelslike_f}</h2>
`;
  }))
  document.querySelector(".results").innerHTML = output;
}
<form id="weather-form">
  <input type="text" class="search">
  <input type="submit" value="submit">
</form>
<div class="results"></div>

rentArray.forEach不是一个函数。这是我的代码: 我认为这与我的let currentArray = resp.current的方式有关,但是我不确定。任何帮助将不胜感激。如果您想更好地看一下,这是我的Codepen的链接。

https://codepen.io/Brushel/pen/JBGGYp?editors=1011

1 个答案:

答案 0 :(得分:2)

API仅返回单个对象,而不返回对象数组。修复showWeather,使其仅访问对象的属性,而不尝试遍历数组:

const weatherForm = document.querySelector("#weather-form");
weatherForm.addEventListener("submit", fetchWeather);

function fetchWeather(e) {
  e.preventDefault();
  
  const searchTerm = document.querySelector(".search").value;
  fetch(`https://api.apixu.com/v1/current.json?key=c54944da22b147b48ec152033160205&q=${searchTerm}`)
  .then((response) => {return response.json(); })
  .then((resp => {
   // console.log(resp);
    let currentArray = resp.current;
    // console.log(currentArray);
    showWeather(currentArray);
  }))
  .catch(err => console.log(err));
}

function showWeather(weatherData) {
  document.querySelector(".results").innerHTML = `
  <div class="container">
    <h2>${weatherData.feelslike_f}</h2>
  </div>
  `;
}
<form id="weather-form">
  <input type="text" class="search">
  <input type="submit" value="submit">
</form>
<div class="results"></div>