首页 > 解决方案 > Javascript fetch api 返回 200 和响应但是.then 不能工作

问题描述

我正在尝试 web 上的 openweathermap api。fetch 确实返回 200 ok 和响应,但以下.then似乎不起作用或从 fetch 继承,因为我无法在 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;
    }
  }

}

标签: javascriptapifetchfetch-apiopenweathermap

解决方案


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

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;

  ...

推荐阅读