我正在使用ReactJS和地理位置(导航器)API和Darksky天气API构建天气应用程序。我得到了经度和纬度显示正确,但当我试图检索数据时,我得到了
代码:400,错误:“给定位置(或时间)无效。”
. 但是,如果我手动将地址放入浏览器,我会得到正确的JSON返回。
URL请求示例:
https://api.darksky.net/forecast/
API U密钥/37.4498,-77.3047
查看控制台中的标题,它甚至没有显示请求的URL包含我传入的经度和纬度。可能是在我得到纬度和经度之前执行了天气API调用吗?
每个控制台的请求URL:
https://api.darksky.net/预测/
api_秘密_密钥/,
getWeather = async (e) => {
let latitude = '';
let longitude = '';
e.preventDefault();
if ("geolocation" in navigator) {
navigator.geolocation.getCurrentPosition((position) => {
latitude = position.coords.latitude.toFixed(4);
longitude = position.coords.longitude.toFixed(4);
console.log("Latitude: " + latitude + ", Longitude: " + longitude);
});
} else {
console.log("Geolocation not available");
}
const weather_api_call = await fetch(`https://api.darksky.net/forecast/${api_secret_key}/${latitude},${longitude}`);
const weather_data = await weather_api_call.json();
console.log(weather_data);
}
答:最终将气象API数据的获取和记录移动到getcurrentPosition函数中
getWeather = (e) => {
e.preventDefault();
if ("geolocation" in navigator) {
navigator.geolocation.getCurrentPosition(async (position) => {
let latitude = position.coords.latitude.toFixed(4);
let longitude = position.coords.longitude.toFixed(4);
console.log("Latitude: " + latitude + " Longitude: " + longitude);
const weather_api_call = await fetch(`https://api.darksky.net/forecast/${api_secret_key}/`+latitude+`,`+longitude);
const weather_data = await weather_api_call.json();
console.log(weather_data);
});
} else {
console.log("Geolocation not available");
}
}