Intro to JavaScript Fetch
The Fetch API is the default tool to make network in web applications. While fetch()
is generally easy to use, there some nuances to be aware of.
In this post, you’ll find the common scenarios of how to use fetch()
with async/await
syntax. You’ll understand how to fetch data, handle fetch errors, cancel a fetch request, and more.
Intro to fetch()
The Fetch API accesses resources across the network. You can make HTTP requests (using GET
, POST
and other methods), download, and upload files.
To start a request, call the special function fetch()
:
const response = await fetch(resource[, options]);
which accepts 2 arguments:
resource
: the URL string, or a Request objectoptions
: the configuration object with properties likemethod
,headers
,body
,credentials
, and more.
fetch()
starts a request and returns a promise. When the request completes, the promise is resolved with the Response object. If the request fails due to some network problems, the promise is rejected.
async/await
syntax fits great with fetch()
because it simplifies the work with promises.
This is an example of how to make a request to fetch in JavaScript.