Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

My fetch requests are being canceled and i don't know why

I am creating a web app that consumes the https://restcountries.eu/ API.

When a user types a country, I'll make a request to the API using fetch. However, my requests always get canceled.

I tested the part which captures user input, but I think the problem is with my fetch code.

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

like image 715
Marcus Neves Avatar asked Oct 31 '20 06:10

Marcus Neves


People also ask

Can fetch request be canceled?

To be able to cancel fetch , pass the signal property of an AbortController as a fetch option: let controller = new AbortController(); fetch(url, { signal: controller. signal }); The fetch method knows how to work with AbortController .

What is fetch TypeError failed?

The "TypeError: Failed to fetch" occurs for multiple reasons: An incorrect or incomplete URL has been passed to the fetch() method. The server you are making a request to does not send back the correct CORS headers. A wrong protocol is specified in the url.

Does fetch send a GET request?

With the fetch() function, we can make GET and POST requests to different URLs. We can configure a fetch() requests to use any HTTP method we want to use. The fetch() function also provides a response object that can be parsed into various formats. These include JSON, text, and bytes to name a few.


1 Answers

One of the reasons for cancelled fetch calls can be that the HTML tag that triggers the event is a child (or grandchild) of an HTML Form tag. In that case the event might trigger the form which will start submitting the form data, thus it will naturally cancel your fetch call.

One of the solutions is to call preventDefault function on the event that triggers the fetch call. See example below:

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

<button onclick="myFetchFunction">Fetch</button>
like image 111
theVoogie Avatar answered Oct 01 '22 16:10

theVoogie