The fetch api is really helpful but unfortunately it doesn't work for most browsers especially internet explorer. I tried to convert my code from es6 to es5 using babel but it doesn't solve this issue. It still includes fetch when it is converted to es5. How can I get around this issue. Here is the es6 code:
var btnText = document.getElementById('btnText');
var btnJson = document.getElementById('btnJson');
btnText.addEventListener("click",fetchBtnText);
function fetchBtnText() {
fetch("sample.txt")
.then((response) => response.text())
.then((data) => console.log(data))
}
Here is the conversion to es5
'use strict';
var btnText = document.getElementById('btnText');
var btnJson = document.getElementById('btnJson');
btnText.addEventListener("click", fetchBtnText);
function fetchBtnText() {
fetch("sample.txt").then(function (response) {
return response.text();
}).then(function (data) {
return console.log(data);
});
}
Just put the API URL in the fetch method. After you have to apply the then() method. If the API request is successfully sent to the server, then this then() method will resolve. And it will send the response data in the format of JSON ( JavaScript Object Notation ).
The Fetch API is a simpler, easy-to-use version of XMLHttpRequest to consume resources asynchronously. Fetch lets you work with REST APIs with additional options like caching data, reading streaming responses, and more. The major difference is that Fetch works with promises, not callbacks.
The Fetch API provides a JavaScript interface for accessing and manipulating parts of the protocol, such as requests and responses. It also provides a global fetch() method that provides an easy, logical way to fetch resources asynchronously across the network.
You could use a polyfill, like this https://github.com/github/fetch
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