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