Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Babel doesn't convert fetch api code

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);
  });
}
like image 971
The Star Avatar asked Mar 15 '18 17:03

The Star


People also ask

How do you get data from an API using Fetch?

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 ).

Is fetch API rest?

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.

What is the use of fetch API?

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.


1 Answers

You could use a polyfill, like this https://github.com/github/fetch

like image 103
TKoL Avatar answered Sep 18 '22 14:09

TKoL