What is cross-fetch?
The cross-fetch npm package is a polyfill for the Fetch API that works in both browser and Node.js environments. It allows you to make HTTP requests using the same API across different platforms, providing a consistent way to fetch resources asynchronously over the network.
What are cross-fetch's main functionalities?
Performing HTTP GET requests
This code sample demonstrates how to perform a simple HTTP GET request to retrieve data from a specified URL and then process the JSON response.
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
Performing HTTP POST requests
This code sample shows how to perform an HTTP POST request to send JSON data to a server and then handle the JSON response.
fetch('https://api.example.com/data', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ key: 'value' })
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
Handling HTTP errors
This code sample illustrates how to handle errors in HTTP requests by checking the response status and throwing an error if the response is not successful.
fetch('https://api.example.com/data')
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
Other packages similar to cross-fetch
axios
Axios is a popular HTTP client for the browser and Node.js. It provides a promise-based API and has a similar feature set to cross-fetch, including the ability to make GET, POST, and other types of HTTP requests. Axios also includes interceptors for request and response transformation, which cross-fetch does not have.
node-fetch
node-fetch is a lightweight module that brings the Fetch API to Node.js. It is similar to cross-fetch but is specifically designed for Node.js environments and does not work in the browser. node-fetch is a good choice if you only need to support server-side fetching.
isomorphic-fetch
isomorphic-fetch is another Fetch API polyfill that works in both Node.js and browser environments. It is similar to cross-fetch in its goal to provide a consistent API across platforms. However, isomorphic-fetch has not been updated as frequently as cross-fetch, which may be a consideration for developers looking for a well-maintained package.
whatwg-fetch
whatwg-fetch is a polyfill for the Fetch API for browsers. It is maintained by the GitHub team and is intended to be used in browser environments only. Unlike cross-fetch, it does not provide Node.js support, making it less versatile for isomorphic applications.
cross-fetch
Universal WHATWG Fetch API for Node, Browsers and React Native.
Installation
npm install --save cross-fetch
Usage
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);
});
FAQ
Yet another fetch library?
My preferred library used to be isomorphic-fetch. It worked all and fine until the day I needed to expand my isomorphic app to React Native. It just threw an exception. I went to the github project and an issue had already been filled. The repo however haven't received a single commit since 2016 leaving us orphans. A lot of forks has been created but each one addresses their particular problem be it cookies, older browsers support or whatever.
In order to run a fetch that is cross-platform compatible, cross-fetch has been created. It is just the same isomorphic-fetch but updated and that bug fixed.
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.
Where can I find the API docs?
You can find a comprehensive doc at Github's fetch page.
Warnings
- This adds
fetch
as a global so that its API is consistent between browsers, node and react-native. - If you're in an environment that doesn't support Promises, you must bring your own ES6 Promise compatible polyfill. es6-promise is suggested.
- For ease-of-maintenance and backward-compatibility reasons, this library will always be a polyfill. As a "safe" alternative, which does not modify the global, consider fetch-ponyfill.
Support
- Node 4+
- React-Native
- Browsers
- Chrome
- Firefox
- Safari 6.1+
- Internet Explorer 10+
Note: modern browsers such as Chrome, Firefox, Microsoft Edge, and Safari contain native implementations of window.fetch
, therefore the code from this polyfill doesn't have any effect on those browsers. If you believe you've encountered an error
with how window.fetch
is implemented in any of these browsers, you should file an issue with that browser vendor instead of this project.
Thanks
Heavily inspired by the works of matthew-andrews. Kudos to him!
License
cross-fetch is licenced under the MIT licence.