javascript

How to Use Fetch API in Javascript

In this tutorial, we are going to use the Fetch API to fetch all public holidays in the United States.

We’ve have written extensively on the Fetch API here.

So, let’s begin.

  getUsHolidays = async () => {
   const url = "https://date.nager.at/api/v2/publicholidays/2020/US";
    const obj = {
      method: "GET",
      headers: {
        Accept: "application/json",
        "Content-Type": "application/json",
      },
    };
    await fetch(`${url}`, obj)
      .then((response) => response.json())
      .then((responseJson) => {
        console.warn(responseJson);

      })
      .catch((error) => {
      console.error(error.message);
      });
  }

Explanation:

Here, we’re using async/await with GET request method, and the content type is application/json.

We’re getting the response on the console and we’re also catching errors as well because, should the request not go through, we want to know what happened.

Result:

Fetch API in Javascript

Conclusion:

Here’s how we can make a simple GET request using Fetch API in Javascript. Let me know what you think in the comments.

check out the official documentaton here

Author

Recent Posts

Google Launches Its Own ‘Reasoning’ AI Model to Compete with OpenAI

This month has been packed for Google as it ramps up efforts to outshine OpenAI…

1 day ago

You can now use your phone line to call ChatGPT when cellular data is unavailable.

OpenAI has been rolling out a series of exciting updates and features for ChatGPT, and…

3 days ago

Phishers use fake Google Calendar invites to target victims

A financially motivated phishing campaign has targeted around 300 organizations, with over 4,000 spoofed emails…

4 days ago

Hackers Exploiting Microsoft Teams to Remotely Access Users’ Systems

Hackers are exploiting Microsoft Teams to deceive users into installing remote access tools, granting attackers…

5 days ago

Ethical Hacking Essentials

Data plays an essential role in our lives.  We each consume and produce huge amounts…

6 days ago

Thomas E. Kurtz, co-creator of the BASIC programming language, passes away at 96.

Thomas E. Kurtz, co-creator of the BASIC programming language, passed away on November 12, 2024,…

6 days ago