GET requests

Andrijan Portrait

Andrijan Tasevski ยท 14 Oct, 2022

Fetch API

fetch("https://catfact.ninja/fact")
  .then((res) => res.json())
  .then((data) => console.log(data))
  .catch((err) => console.log(err));

Async function

async function fetchData() {
  // Code to execute before fetching data
  try {
    const res = await fetch("https://catfact.ninja/fact");

    if (!res.ok) {
      throw Error(res.statusText);
    }

    const data = await res.json();

    console.log(data);
  } catch (err) {
    // Handle errors here
    console.log(err);
  } finally {
    // Code to execute regardless of promise result
  }
}

fetchData();

Axios

axios
  .get("https://catfact.ninja/fact")
  .then((res) => {
    // handle success
    console.log(response);
  })
  .catch((error) => {
    // handle error
    console.log(error);
  })
  .then(() => {
    // always executed
  });

Usage of axios

We can use axios both in the browser and in a node environment.

To use axios in the browser, we include the following script in our HTML:

<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>

To use axios in a node environment, we run the following command in a terminal:

npm i axios

Then, we import axios:

import axios from "axios";