简体   繁体   中英

I'm trying to fetch a JSON file from an API

So I'm creating a new tab extension for chrome and I want to display the weather for the user. To do this I am using the geolocation API for the location and then openweather API for the weather data. The problem I have is when I use the fetch method it look for the file locally, this url :

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

But I want it to look for the file on the internet, how do I solve this?

This is the code I am currently using.

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);
            });
        });


      });
}

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

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

Fetch is a Promise that returns a response.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM