Languages
[Edit]
EN

JavaScript - GET request with fetch method

0 points
Created by:
Dirask JS Member
3460

In this article, we would like to show you how to make GET requests with JavaScript Fetch API.

We will present 3 examples of GET request with the fetch method:

  1. basic promises based example,
  2. async-await - promises mixed based example with basic error protection
  3. async-await based example with basic error protection

The choice of method depends on the situation in which we want to use it, but the last approach is the most recommended in most cases.

1. Basic promises based example

This approach is fine, but with complex code, it gets a lot of callback and the code becomes quite unreadable.

Note: 

You need to add a status check here as it is done in the following examples

// ONLINE-RUNNER:browser;

<!DOCTYPE html>
<html>
<body>
  <script>

    fetch('/examples/echo?text=hello')
        .then((response) => response.text())
        .then((text) => console.log(text))
        .catch((error) => console.error(error));
    
  </script>
</body>
</html>

2. async-await - promises mixed based

In the presented approach, we used promises with async-await, so that you do not have to wrap the fetch function with the asynchronous method.

// ONLINE-RUNNER:browser;

<!DOCTYPE html>
<html>
<body>
  <script>

    fetch('/examples/echo?text=hello')
        .then(async (response) => {
            if (response.status == 200) {
                const text = await response.text();
                console.log(`Received data: ${text}`);
            } else {
                console.log(`Received error: status=${response.status}`);
            }
        })
        .catch((error) => {
            console.error(`Occured exception: ${error}`);
        });
    
  </script>
</body>
</html>

3. async-await based example with basic error protection

The last example is based on async-await - the advantage of this approach is readability and more convenient handling (most recommended).

// ONLINE-RUNNER:browser;

<!DOCTYPE html>
<html>
<body>
  <script>

    const doGet = async () => {
        try {
            const response = await fetch('/examples/echo?text=hello');
            if (response.status == 200) {
                const text = await response.text();
                console.log(`Received data: ${text}`);
            } else {
                console.log(
                    `Received error: status=${response.status}`
                );
            }
        } catch (error) {
            console.error(`Occured exception: ${error}`);
        }
    };

    doGet();
    
  </script>
</body>
</html>

Resources

  1. Fetch API - MDN Docs
Native Advertising
­čÜÇ
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

ÔŁĄ´ŞĆ­čĺ╗ ­čÖé

Join