Javascript fetch api返回200并且响应但是。然后无法工作

问题描述 投票:0回答:1

我在网上尝试openweathermap api。获取确实返回200 ok和响应但是以下。然后似乎无法工作或从fetch继承,因为我无法在console.log,alert或print to 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;
    }
  }

}
javascript api fetch fetch-api openweathermap
1个回答
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;

  ...
© www.soinside.com 2019 - 2024. All rights reserved.