Socket
Socket
Sign inDemoInstall

cross-fetch

Package Overview
Dependencies
6
Maintainers
1
Versions
49
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

    cross-fetch

Universal WHATWG Fetch API for Node, Browsers and React Native


Version published
Maintainers
1
Install size
604 kB
Created

Package description

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

Readme

Source

cross-fetch Build Status NPM Version License: MIT

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:

// Using ES6 modules
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');

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:

  • Simple import / require (no configuration required)
  • Platform agnostic (client, server or react native)
  • Optional polyfill (it's up to you if something is going to be added to the global object or not)

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á

Keywords

FAQs

Last updated on 30 Sep 2017

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.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc