【问题标题】:I'm trying to fetch a JSON file from an API我正在尝试从 API 获取 JSON 文件
【发布时间】:2019-07-10 11:19:00
【问题描述】:

所以我正在为 chrome 创建一个新的标签扩展,我想为用户显示天气。为此,我使用地理定位 API 获取位置,然后使用 openweather API 获取天气数据。我遇到的问题是,当我使用 fetch 方法时,它会在本地查找文件,这个 url :

chrome-extension://kgimldinjffdncnfpgflgjeaiafjdflp/api.openweathermap.org/data/2.5/weather?lat=56.692819099999994+&lon=12.8946167。

但我想让它在网上找文件,我该如何解决?

这是我目前正在使用的代码。

var OpenWeather;
if("geolocation" in navigator){
      // check if geolocation is supported/enabled on current browser
      navigator.geolocation.getCurrentPosition(function(position:Position){
        fetch("api.openweathermap.org/data/2.5/weather?lat="+position.coords.latitude+"+&lon="+position.coords.longitude).then(function(response){
            response.json().then(function(data){
                OpenWeather=data;
                alert(OpenWeather);
            });
        });


      });
}

【问题讨论】:

    标签: javascript typescript


    【解决方案1】:

    在 API url 中添加 https,如下所示:

     fetch("https://api.openweathermap.org/data/2.5/weather?lat="+position.coords.latitude+"+&lon="+position.coords.longitude) 
    

    【讨论】:

      【解决方案2】:

      Fetch 是一个返回响应的 Promise。

      fetch(url).then(res => res.json()).then(json=> {});
      // or
      fetch(url).then(function (res) {
         return res.json();
      }).then(function (json) {});
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-10-01
        • 2021-11-16
        • 2021-02-13
        • 2020-04-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多