参考错误。未定义API (Javascript)

问题描述 投票:0回答:2

我想为meteo做一个App,但是我的api没有加载,当我在fetch中调用api时,它的输出是。ReferenceError: API is not definedIt is my first app (also my first question on StackOverflow), this is the snippet:

window.addEventListener('load', () =>{
  let long;
  let lang;
  let temperatureDescription = document.querySelector('.temperature-description');
  let temperatureDegree = document.querySelector('.temperature-degree');
  let locationTimezone = document.querySelector('.location-timezone');
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(position=>{
      long = position.coords.longitude;
      lat = position.coords.latitude;
      const proxy = 'https://cors-anyware.herouapp.com/';
      const API = '${proxy}https://api.openweathermap.org/data/2.5/forecast?id=524901&APPID=cc6a4a00070dfbee1327390b072f88d6/${lat},${long}';
    });
    fetch(API).then(response=>{
      return response.json();
    }).then(data=>{
      console.log(data);
      const {
        temperature,
        summary
      }
      = data.currently;
      //set DOM elements from the API
      temperatureDegree.textContent = temperature;
    });
  };
}
);

谁能帮帮我?)

javascript api fetch-api
2个回答
0
投票

你的 API 常量变量是块范围的,这意味着它只能在getCurrentPosition函数的回调中被访问。

还有navigator.geolocation.getCurrentPosition 是异步的,你应该调用 fetch 否则 fetch 将在浏览器检测到位置纬度之前执行。

window.addEventListener('load', () =>{
  let long;
  let lang;
  let temperatureDescription = document.querySelector('.temperature-description');
  let temperatureDegree = document.querySelector('.temperature-degree');
  let locationTimezone = document.querySelector('.location-timezone');
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(position=>{
      long = position.coords.longitude;
      lat = position.coords.latitude;
      const proxy = 'https://cors-anyware.herouapp.com/';
      const API = '${proxy}https://api.openweathermap.org/data/2.5/forecast?id=524901&APPID=cc6a4a00070dfbee1327390b072f88d6/${lat},${long}';

      fetch(API).then(response=>{
          return response.json();
      }).then(data=>{
          console.log(data);
          const {
            temperature,
            summary
          }
         = data.currently;
        //set DOM elements from the API
        temperatureDegree.textContent = temperature;
      });
    });

  };
}
);

© www.soinside.com 2019 - 2024. All rights reserved.