解决React JS中的API调用问题(400错误)

时间:2018-11-25 00:59:37

标签: javascript json reactjs api fetch

我正在使用reactjs和geolocation(navigator)api和darksky weather api构建一个Weather App。我正确显示了经度和纬度,但是当我尝试检索数据时,得到了 {code:400,error:“给定的位置(或时间)无效。”} 。但是,如果我手动将地址放入浏览器,则会返回正确的JSON。

URL请求示例:https://api.darksky.net/forecast/ {api_secret_key} /37.4498,-77.3047

在控制台的标题中,甚至都没有出现所请求的URL包含我要传递的经度和纬度。可能是在获取纬度和经度之前正在执行天气API调用吗?

每个控制台的请求URL:https://api.darksky.net/forecast/ {api_secret_key} /,

  getWeather = async (e) => { //Get weather data
    let latitude = '';
    let longitude = '';
    e.preventDefault(); //prevent page reload behaviour
    if ("geolocation" in navigator) {
      navigator.geolocation.getCurrentPosition((position) => {
        latitude = position.coords.latitude.toFixed(4); //save lat and lon from above API call
        longitude = position.coords.longitude.toFixed(4);

        console.log("Latitude: " + latitude + ", Longitude: " + longitude);

      });
    } else {
      console.log("Geolocation not available");
    }

    //Pass the lattitude and longitude values from the location API call to the weather API
    const weather_api_call = await fetch(`https://api.darksky.net/forecast/${api_secret_key}/${latitude},${longitude}`);
    const weather_data = await weather_api_call.json(); //retrieve weather API data

    console.log(weather_data); //print weather API data to console
  }

答案:最终将天气API数据的获取和记录移至getCurrentPosition函数中

  getWeather = (e) => {
    e.preventDefault(); //prevent page reload behaviour

    if ("geolocation" in navigator) { //if the users allows geolocation to be active
      navigator.geolocation.getCurrentPosition(async (position) => {  //access naviagotr API & get the users current lat and lon

        let latitude = position.coords.latitude.toFixed(4); //save lat and lon from above API call
        let longitude = position.coords.longitude.toFixed(4);

         console.log("Latitude: " + latitude + " Longitude: " + longitude); //check lat and lon 

          //Pass the lattitude and longitude values from the location API call to the weather API
          const weather_api_call = await fetch(`https://api.darksky.net/forecast/${api_secret_key}/`+latitude+`,`+longitude); //run API call after when lat and lon data is gotten
          const weather_data = await weather_api_call.json(); //retrieve weather API data after the call is executed with the lat and lon

          console.log(weather_data); //print weather API data to console

      });
    } else {
      console.log("Geolocation not available"); //Log if user blocks location in browser
  }
}

1 个答案:

答案 0 :(得分:0)

navigator.geolocation.getCurrentPosition是一个异步调用,您可以在提供的回调中设置纬度和经度的值。但是getWeather函数会一直执行并使用原始的经度和纬度值(定义为空字符串)调用获取。

如果将提取调用移至navigator.geolocation.getCurrentPosition的回调中,则可以确定定义了纬度和经度。