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())
})
}
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 .
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.
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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With