cross-fetch
Universal WHATWG Fetch API for Node, Browsers and React Native. The scenario that cross-fetch really shines is when the same javascript codebase needs to run on different platforms.
Installation
npm install --save cross-fetch
As a ponyfill:
import { fetch } from 'cross-fetch';
const { fetch } = require('cross-fetch');
As a polyfill:
import 'cross-fetch/polyfill';
require('cross-fetch/polyfill');
Usage
As a ponyfill:
const { fetch } = require('cross-fetch');
fetch('//api.github.com/users/lquixada')
.then(res => {
if (res.status >= 400) {
throw new Error("Bad response from server");
}
return res.json();
})
.then(user => {
console.log(user);
});
As a polyfill:
require('cross-fetch');
fetch('//api.github.com/users/lquixada')
.then(res => {
if (res.status >= 400) {
throw new Error("Bad response from server");
}
return res.json();
})
.then(user => {
console.log(user);
});
⚠️ Warning: If you're in an environment that doesn't support Promises such as Internet Explorer, you must install an ES6 Promise compatible polyfill. es6-promise is suggested.
API
You can find a comprehensive doc at Github's fetch page.
FAQ
Yet another fetch library?
I did a lot of research in order to find a fetch library that could meet theses criterias:
There's a plethora of libs out there but none could match those.
Why not isomorphic-fetch?
My preferred library used to be isomorphic-fetch but it has this bug that prevents it from running in a react native environment. Also, polyfilling is mandatory.
How does it work?
cross-fetch (like isomorphic-fetch) is just a proxy. If you're in node, it delivers you the node-fetch library, if you're in a browser ou React Native, it delivers you the github's whatwg-fetch. The same strategy applies if you're using polyfill or ponyfill.
Suported environments
- Node 4+
- React-Native
- Browsers
- Chrome
- Firefox
- Safari 6.1+
- Internet Explorer 10+
Thanks
Heavily inspired by the works of matthew-andrews. Kudos to him!
License
cross-fetch is licenced under the MIT licence © Leonardo Quixadá