Security News
RubyGems.org Adds New Maintainer Role
RubyGems.org has added a new "maintainer" role that allows for publishing new versions of gems. This new permission type is aimed at improving security for gem owners and the service overall.
cross-fetch
Advanced tools
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.
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));
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 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 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 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.
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.
npm install --save cross-fetch
As a ponyfill:
// Using ES6 modules with Babel or TypeScript
import fetch from 'cross-fetch';
// Using CommonJS modules
const fetch = require('cross-fetch');
As a polyfill:
// Using ES6 modules
import 'cross-fetch/polyfill';
// Using CommonJS modules
require('cross-fetch/polyfill');
The CDN build is also available on unpkg:
<script src="//unpkg.com/cross-fetch/dist/cross-fetch.js"></script>
This adds the fetch function to the window object. Note that this is not UMD compatible.
With promises:
import fetch from 'cross-fetch';
// Or just: import 'cross-fetch/polyfill';
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);
})
.catch(err => {
console.error(err);
});
With async/await:
import fetch from 'cross-fetch';
// Or just: import 'cross-fetch/polyfill';
(async () => {
try {
const res = await fetch('//api.github.com/users/lquixada');
if (res.status >= 400) {
throw new Error("Bad response from server");
}
const user = await res.json();
console.log(user);
} catch (err) {
console.error(err);
}
})();
⚠️ 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.
You can find a comprehensive doc at Github's fetch page. If you want to play with cross-fetch, these resources can be useful:
Tip: Run theses resources on various browsers and with different settings (for instance: cross-domain requests, wrong urls or text requests). Don't forget to open the console in the test suite page and play around.
I did a lot of research in order to find a fetch library that could be simple, cross-platorm and provide polyfill as an option. There's a plethora of libs out there but none could match those requirements.
My preferred library used to be isomorphic-fetch but it has this bug that prevents it from running in a react native environment. It seems it will never be fixed since the author hasn't been commiting for more than a year. That means dependencies are outdated as well.
In a word? Risk. If the spec changes in the future, it might be problematic to debug. Read more about it on sindresorhus's ponyfill page. It's up to you if you're fine with it or not.
Just like isomorphic-fetch, it is just a proxy. If you're in node, it delivers you the node-fetch library, if you're in a browser or React Native, it delivers you the github's whatwg-fetch. The same strategy applies whether you're using polyfill or ponyfill.
Heavily inspired by the works of matthew-andrews. Kudos to him!
cross-fetch is licensed under the MIT license © Leonardo Quixadá
@lquixada |
Manual cross-browser testing is provided by the following sponsor:
FAQs
Universal WHATWG Fetch API for Node, Browsers and React Native
The npm package cross-fetch receives a total of 12,378,851 weekly downloads. As such, cross-fetch popularity was classified as popular.
We found that cross-fetch demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
RubyGems.org has added a new "maintainer" role that allows for publishing new versions of gems. This new permission type is aimed at improving security for gem owners and the service overall.
Security News
Node.js will be enforcing stricter semver-major PR policies a month before major releases to enhance stability and ensure reliable release candidates.
Security News
Research
Socket's threat research team has detected five malicious npm packages targeting Roblox developers, deploying malware to steal credentials and personal data.