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

Using in Node.js

1
yarn add node-fetch
Copied!
Importing:
fetch-import-success.ts
1
import fetch from 'node-fetch';
Copied!
If you use webpack, the following will work locally, but fail when deployed in webpack.
fetch-webpack-import-fail.ts
1
import * as fetch from 'node-fetch';
Copied!

Text:

fetch-text.ts
1
const response = await fetch(url);
2
console.log(response);
3
const text = await response.text();
Copied!
response:
fetch-text-response.ts
1
{
2
ok true,
3
status: 200,
4
...
5
}
Copied!

JSON:

fetch-json.ts
1
const response = await fetch(url);
2
const json = await response.json();
Copied!

Errors Handling

    No errors are thrown.
    No need for try/catch
fetch-error.ts
1
const response = await fetch(url);
2
console.log(response);
3
if (!response.ok) {
4
...
5
}
Copied!
response:
fetch-error-response.json
1
{
2
ok false,
3
status: 404,
4
}
Copied!
Last modified 2yr ago