我想从天气 api 中提取数据,但出现了一些错误

I want to pull data from the Weather api but getting some errors

我收到这些错误:

  1. GET http://127.0.0.1:5500/src/api.openweathermap.org/data/2.5/weather?lat=29.0188653&lon=77.7680952&appid=9268356eb17fbbe77a86201da74c9c46 404(未找到)
  2. 未捕获(承诺)语法错误:JSON 中位置 0
  3. 中的意外标记 <

JavaScript

window.addEventListener("load", () => {
  let lon;
  let lat;
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition((postion) => {
      lat = postion.coords.latitude;
      lon = postion.coords.longitude;
      const api = `api.openweathermap.org/data/2.5/weather? 
           lat=${lat}&lon=${lon}&appid=9268356eb17fbbe77a86201da74c9c46`;
      fetch(api)
        .then((response) => {
          return response.json();
        })
        .then((data) => {
          console.log(data);a
        })
        .catch((err) => alert("Enable your location"));
    });
    // else{
    //     alert("Geolocation is not supported by this browser.";);
    // }
  }
});

尝试将 https:// 添加到 URL 像这样

 const api = `https://api.openweathermap.org/data/2.5/weather? 
           lat=${lat}&lon=${lon}&appid=9268356eb17fbbe77a86201da74c9c46`;

您的本地开发环境应该是安全的,即您需要使用 https://localhosthttps://127.0.0.1 来检索您用户的纬度和经纬度数据,在本例中是您自己的。

使用此设置在您的本地计算机上创建 https 证书,https://github.com/FiloSottile/mkcert

另外,你需要这个link作为指导,https://www.section.io/engineering-education/how-to-get-ssl-https-for-localhost/

参考: https://developer.mozilla.org/en-US/docs/Web/API/Geolocation/getCurrentPosition

navigator.geolocation.getCurrentPosition 应该在安全的环境中,即使它是本地主机。