我正在尝试使用 OpenWeatherApi 编写一个根据您当前位置显示温度的天气应用程序,我收到错误 404 我不知道为什么
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(position => {
long = position.coords.longitude;
lat = position.coords.latitude;
console.log(position);
const api = `api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${long}&appid=74913cd6ec927a299e7fd99534e17b5f`;
fetch(api)
.then(response => {
return response.json();
})
.then(data => {
console.log(data);
});
});
我在控制台中遇到的错误:
最佳答案
您需要在 URL 前面添加 https://
。例如,
❌api.openweathermap.org/data/2.5/forecast?lat={lat}&lon={lon}&appid={API key }
✅ https://api.openweathermap.org/data/2.5/forecast?lat={lat}&lon={lon}&appid={API key }
OpenWeather 上的 API 调用有时会从其网站上的 API 调用 URL 中排除 https://
。但是,当在 JS 代码中进行 API 调用时,您不能省略这一点,否则您的代码会将您的 URL 转换为相对路径。
关于javascript - 使用 Openweathermap API 出现找不到 http 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63092309/