我想为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;
});
};
}
);
谁能帮帮我?)
你的 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;
});
});
};
}
);