我的提取请求被取消,我不知道为什么

时间:2020-10-31 06:40:50

标签: javascript fetch

我正在创建一个使用https://restcountries.eu/ API的网络应用。

当用户输入国家/地区时,我将使用fetch向API发出请求。但是,我的请求总是被取消。

我测试了捕获用户输入的部分,但我认为问题出在我的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())
})
}

IMAGE: I always receive this error in the network

IMAGE: And this error in console

3 个答案:

答案 0 :(得分:1)

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

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

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

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

答案 1 :(得分:0)

您的fetch代码在第一个then关闭附近出现语法错误。

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(function(data){
        console.log(data)
    })


}

grabCountry('', '' , '')
<input type="text" id="searchInput" value="united" />

答案 2 :(得分:0)

到目前为止,您提供的代码可以正常工作。您需要检查如何获取数据。对于文本,它应该看起来像这样;对于解析json,它应该看起来像.json()

fetch('/url')
     .then(response => response.text())
     .then(data => console.log(data));

这是一个演示:

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

function grabCountry() {

  countryName = 'Bulgaria';

  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 => response.json())
 .then(data => console.log(data))
}

grabCountry();