Javascript获取API返回200和响应,但.then无法工作

时间:2019-04-01 13:10:06

标签: javascript api fetch fetch-api openweathermap

我正在尝试在网络上使用openweathermap api。提取确实返回了200 ok并返回了响应,但是以下 .then 似乎无法正常工作或继承自提取,因为我无法在console.log,警报或打印到html中操作接收到的数据。

它不显示任何错误或警告。但是只需[HTTP / 1.1 200 OK 637ms]。

请帮助我输入验证码。非常感谢。谢谢...

let weatherInfo = document.getElementById("weatherInfo");

//Trigger on click on HTML 
function submitFormCheck() {

  //Check if text field contain value
  //Check if browser support Geolocation
  const txtBox = document.getElementById('textBoxx').value;
  if (txtBox == "" || txtBox.length == 0 || txtBox == null) {
    //Retrieve the location from callback and fetch api
    getLocation(function(lat_lng) {
      console.log(`longitude: ${ lat_lng.lat } | latitude: ${ lat_lng.lng }`);
      const url = 'https://api.openweathermap.org/data/2.5/forecast?lat=' + lat_lng.lat + '&lon=' + lat_lng.lng + '&APPID=075bd82caf51b82c26d704147ba475da&units=metric';
      const fetchDetails = {
        method: 'GET'
      };

      fetch(url, fetchDetails)
        .then((resp) => resp.json())
        .then((data) => {
          console.log("testing"); //console.log cant work 
          alert("testing"); //alert cant work
          let i = data.city;
          console.log(i.name); // response.data cant print out
        })
        .catch((error) => console.log(error));
    });


  } else {
    return false;
  }

  
  function getLocation(callback) {
    if (navigator.geolocation) {

      let lat_lng = navigator.geolocation.getCurrentPosition(function(position) {
        // get current location by using html 5 geolocation api
        let userPosition = {};
        userPosition.lat = position.coords.latitude;
        userPosition.lng = position.coords.longitude;
        callback(userPosition);

      }, positionHandlingError);
    } else {
      alert("Geolocation is not supported by this browser. Please enter the location manually");
    }
  }



  // if failed to get location
  function positionHandlingError(error) {
    switch (error.code) {
      case error.PERMISSION_DENIED:
        console.log("User denied the request for Geolocation.");
        break;
      case error.POSITION_UNAVAILABLE:
        console.log("Location information is unavailable.");
        break;
      case error.TIMEOUT:
        console.log("The request to get user location timed out.");
        break;
      case error.UNKNOWN_ERROR:
        console.log("An unknown error occurred.");
        break;
    }
  }

}

1 个答案:

答案 0 :(得分:0)

似乎您并没有阻止表单提交的默认行为:

function submitFormCheck(e) {

  //Prevent form submit
  e.preventDefault();

  //Check if text field contain value
  //Check if browser support Geolocation
  const txtBox = document.getElementById('textBoxx').value;

  ...