首页 > 解决方案 > 我的获取请求被取消了,我不知道为什么

问题描述

我正在创建一个使用https://restcountries.eu/ API 的 Web 应用程序。

当用户键入国家/地区时,我将使用fetch. 但是,我的请求总是被取消。

我测试了捕获用户输入的部分,但我认为问题出在我的fetch代码上。

var countryName; // This will receive the user input on a textbox in my HTML file.
var resultado;

function grabCountry(urlendpoint, countryName, endpointfields) {

  countryName = document.getElementById('searchInput').value;

  var urlendpoint = 'https://restcountries.eu/rest/v2/name/';    
  var endpointfields = '?fields=topLevelDomain;alpha3Code;callingCodes;altSpellings;subregion;population;latlng;languages;flag';

fetch(urlendpoint + countryName + endpointfields)
 .then(response => data)
 .then(data => {
   console.log(data())
})
}

图片:我总是在网络中收到此错误

图片:控制台中的这个错误

标签: javascriptfetch

解决方案


取消调用的原因之一fetch可能是触发事件的 HTML 标记是 HTML 表单标记的子(或孙)标记。在这种情况下,该事件可能会触发将开始提交表单数据的表单,因此它自然会取消您的fetch呼叫。

解决方案之一是preventDefault在触发fetch调用的事件上调用函数。请参见下面的示例:

function myFetchFunction(event) {
  event.preventDefault();
  fetch("https://my-url-here");
}

<button onclick="myFetchFunction">Fetch</button>

推荐阅读