Skip to content
Permalink
Branch: master
Find file Copy path
Find file Copy path
Fetching contributors…
Cannot retrieve contributors at this time
108 lines (83 sloc) 2.25 KB

fetch

The Fetch API provides an interface for fetching resources (including across the network). It will seem familiar to anyone who has used XMLHttpRequest, but the new API provides a more powerful and flexible feature set.

Using in Browsers

Not supported on all browsers. You can polyfill using watchwg-fetch

https://npmcompare.com/compare/node-fetch,whatwg-fetch

Using in Node.js

yarn add node-fetch

Importing:

{% code-tabs %} {% code-tabs-item title="fetch-import-success.ts" %}

import fetch from 'node-fetch';

{% endcode-tabs-item %} {% endcode-tabs %}

If you use webpack, the following will work locally, but fail when deployed in webpack.

{% code-tabs %} {% code-tabs-item title="fetch-webpack-import-fail.ts" %}

import * as fetch from 'node-fetch';

{% endcode-tabs-item %} {% endcode-tabs %}

Text:

{% code-tabs %} {% code-tabs-item title="fetch-text.ts" %}

const response = await fetch(url);
console.log(response);
const text = await response.text();

{% endcode-tabs-item %} {% endcode-tabs %}

response:

{% code-tabs %} {% code-tabs-item title="fetch-text-response.ts" %}

{
  ok true,
  status: 200,
  ...
}

{% endcode-tabs-item %} {% endcode-tabs %}

JSON:

{% code-tabs %} {% code-tabs-item title="fetch-json.ts" %}

const response = await fetch(url);
const json = await response.json();

{% endcode-tabs-item %} {% endcode-tabs %}

Errors Handling

  • No errors are thrown.
  • No need for try/catch

{% code-tabs %} {% code-tabs-item title="fetch-error.ts" %}

const response = await fetch(url);
console.log(response);
if (!response.ok) {
  ...
}

{% endcode-tabs-item %} {% endcode-tabs %}

response:

{% code-tabs %} {% code-tabs-item title="fetch-error-response.json" %}

{
  ok false,
  status: 404,
}

{% endcode-tabs-item %} {% endcode-tabs %}

You can’t perform that action at this time.