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.
Not supported on all browsers. You can polyfill using watchwg-fetch
​https://npmcompare.com/compare/node-fetch,whatwg-fetch​
yarn add node-fetch
Importing:
fetch-import-success.tsimport fetch from 'node-fetch';
If you use webpack, the following will work locally, but fail when deployed in webpack.
fetch-webpack-import-fail.tsimport * as fetch from 'node-fetch';
fetch-text.tsconst response = await fetch(url);console.log(response);const text = await response.text();
response
:
fetch-text-response.ts{ok true,status: 200,...}
fetch-json.tsconst response = await fetch(url);const json = await response.json();
No errors are thrown.
No need for try/catch
fetch-error.tsconst response = await fetch(url);console.log(response);if (!response.ok) {...}
response
:
fetch-error-response.json{ok false,status: 404,}