Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ES6 `fetch is undefined`

I'm building a site with ES6 and Babel.

In a script file, I need to make an ajax call to a service on server. For that I'm doing like this:

fetch('url').then(     response => response.json() ).then(     supervisoryItems => doSomething(supervisoryItems) ) 

In Google Chrome this works just fine, but it does not work on Firefox or IE (I'm getting the error fetch is undefined). Searching on Google I found this should fix it:

import promise from 'es6-promise' promise.polyfill() 

Sadly it does not change anything, I have the same issue. Any help?

like image 210
Pablo Avatar asked Apr 07 '16 18:04

Pablo


People also ask

Why fetch is undefined?

The "ReferenceError: fetch is not defined" occurs when the fetch() method is used in an environment where it's not supported - most commonly NodeJs. To solve the error, install and import the node-fetch package, which provides a fetch() compatible API in the NodeJs runtime.

Is node-fetch the same as fetch?

fetch() function. In NodeJS, several packages/libraries can achieve the same result. One of them is the node-fetch package. node-fetch is a lightweight module that enables us to use the fetch() function in NodeJS, with very similar functionality as window.

How define fetch in JavaScript?

The fetch() method in JavaScript is used to request to the server and load the information on the webpages. The request can be of any APIs that return the data of the format JSON or XML. This method returns a promise.

How do I get fetch data?

The Fetch API allows you to asynchronously request for a resource. Use the fetch() method to return a promise that resolves into a Response object. To get the actual data, you call one of the methods of the Response object e.g., text() or json() . These methods resolve into the actual data.


2 Answers

You need to add the 'isomorphic-fetch' module to your 'package.json' and then import this.

npm install --save isomorphic-fetch es6-promise 

Then in your code

import "isomorphic-fetch" 

See https://www.npmjs.com/package/isomorphic-fetch

like image 65
Kieran Johnson Avatar answered Sep 23 '22 06:09

Kieran Johnson


I will use the two following cdn like this:

<script src="//cdn.jsdelivr.net/bluebird/3.5.0/bluebird.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/fetch/2.0.3/fetch.js"></script> 
like image 45
Thomas Avatar answered Sep 22 '22 06:09

Thomas