Movatterモバイル変換


[0]ホーム

URL:


Altcademy Blog

Altcademy - aForbes magazine logo Best Coding Bootcamp 2023

How To ·JavaScript

How to Use the JavaScript Fetch API to Get Data

Altcademy Team

Altcademy Team

4 min

Fetching data from a server or an API (Application Programming Interface) is a common task in web development. JavaScript provides a simple and elegant way to fetch data from a remote source using the Fetch API. In this tutorial, we'll learn about the Fetch API and how you can use it to get data from a server.

Please note: This tutorial is intended for beginners who are learning programming, so we'll try to avoid jargon as much as possible. If we do use any technical terms, we'll make sure to explain them.

What is Fetch API?

The Fetch API is a modern, powerful and flexible way to make HTTP requests in JavaScript. It is built into the language, which means you don't need to include any external libraries to use it. The Fetch API provides a globalfetch() method that can be used to request data from an API or a server. It returns aPromise that resolves to theResponse object representing the response to the request.

Before we dive into the Fetch API, let's quickly understand what aPromise is.

Promises

APromise is a JavaScript object that represents the eventual completion (or failure) of an asynchronous operation and its resulting value. APromise is in one of three states:

  1. Pending: The initial state; neither fulfilled nor rejected.
  2. Fulfilled: The operation completed successfully, and the resulting value is available.
  3. Rejected: The operation failed, and an error reason is available.

APromise is said to be "settled" if it is either fulfilled or rejected. You can attach callbacks to aPromise using the.then() and.catch() methods. The.then() method is called when thePromise is fulfilled, while the.catch() method is called when thePromise is rejected.

Now that we have a basic understanding of Promises, let's dive into using the Fetch API.

Using the Fetch API

Using the Fetch API is quite simple. You just need to call the globalfetch() method and provide the URL of the resource you want to fetch. Thefetch() method returns aPromise that resolves to aResponse object. Let's see an example:

fetch('https://api.example.com/data')  .then(response => {    console.log(response);  })  .catch(error => {    console.error('Error fetching data:', error);  });

In the example above, we are fetching data fromhttps://api.example.com/data. Thefetch() method returns aPromise, and we are using the.then() method to handle the successful response and the.catch() method to handle any errors.

TheResponse object that we receive in the.then() method contains several properties and methods that can be used to extract the data from the response. Some of the most commonly used properties and methods are:

  • response.ok: A boolean value that indicates whether the request was successful (status code in the range 200-299) or not.
  • response.status: The status code of the response (e.g., 200, 404, 500, etc.).
  • response.statusText: A status message corresponding to the status code (e.g., "OK", "Not Found", "Internal Server Error", etc.).
  • response.headers: An object representing the headers of the response.
  • response.json(): A method that returns aPromise that resolves to the JSON object resulting from parsing the response's body text as JSON.
  • response.text(): A method that returns aPromise that resolves to the response's body text as a string.

In most cases, you'll want to extract the JSON data from the response. Let's modify our previous example to parse the JSON data:

fetch('https://api.example.com/data')  .then(response => {    if (!response.ok) {      throw new Error('Network response was not ok');    }    return response.json();  })  .then(data => {    console.log(data);  })  .catch(error => {    console.error('Error fetching data:', error);  });

In this example, we first check if theresponse.ok property istrue. If it is not, we throw an error that will be caught by the.catch() method. Otherwise, we call theresponse.json() method, which returns aPromise that resolves to the JSON data. We then use another.then() method to handle the JSON data.

You can also fetch data in other formats, like text or binary data (e.g., images, audio files, etc.). To fetch data as text, you can use theresponse.text() method, like this:

fetch('https://api.example.com/data.txt')  .then(response => {    if (!response.ok) {      throw new Error('Network response was not ok');    }    return response.text();  })  .then(text => {    console.log(text);  })  .catch(error => {    console.error('Error fetching data:', error);  });

Using Fetch with Async/Await

Another way to handle asynchronous operations in JavaScript is by using theasync/await syntax. This allows you to write asynchronous code that looks and behaves like synchronous code, which makes it easier to read and understand.

To useasync/await with the Fetch API, you need to follow these steps:

  1. Declare anasync function. This tells JavaScript that the function will contain asynchronous code.
  2. Inside theasync function, use theawait keyword before calling thefetch() method. This tells JavaScript to wait for thePromise to resolve before continuing with the rest of the code.
  3. Usetry/catch blocks to handle errors.

Here's an example of how to use the Fetch API withasync/await:

async function fetchData() {  try {    const response = await fetch('https://api.example.com/data');    if (!response.ok) {      throw new Error('Network response was not ok');    }    const data = await response.json();    console.log(data);  } catch (error) {    console.error('Error fetching data:', error);  }}fetchData();

In this example, we've declared anasync function calledfetchData(). Inside this function, we use theawait keyword before calling thefetch() method and theresponse.json() method. This makes the code easier to read and understand.

Conclusion

In this tutorial, we learned about the JavaScript Fetch API and how to use it to fetch data from an API or a server. We also learned about Promises and how to handle asynchronous operations using the.then() and.catch() methods, as well as theasync/await syntax.

The Fetch API is a powerful and flexible way to make HTTP requests in JavaScript, and it is an essential tool

Read next

How to style two classes in ReactJS as under each other

Getting StartedWelcome to another tutorial, dear reader! Today, we'll be diving into the world of ReactJS, a popular library used for building interactive user interfaces. Specifically, we're going to explore how to style two classes in ReactJS as under each other.Now, you might be wondering, "What does it
By Altcademy Team

How to set options as values from a json object in ReactJS

Understanding JSON and its Role in ReactJSBefore diving into the main topic, let's quickly understand what JSON is. JSON, an acronym for JavaScript Object Notation, is a lightweight format for storing and transferring data. It's often used when data is sent from a server to a web page. It's
By Altcademy Team

How to use ReactJS in atom

Getting Started with ReactJS in AtomFirst and foremost, we need to understand what ReactJS and Atom are. ReactJS is a JavaScript library that helps us to build user interfaces (the parts of a website you interact with). Atom, on the other hand, is a text editor where we write
By Altcademy Team

Learn to code in our100% online programs

Altcademy coding bootcamp offersbeginner-friendly, online programs designed byindustry experts to help you become a coder.85%+ ofAltcademy alumni are hired within 6 months after graduation. Seehow we teach, or click on one of the following programs to find out more.

Most Popular

Most Popular7 Courses

FSWD

Front-end
Back-end

Full-stack Web Development

Learn full-stack development with HTML, CSS, JavaScript, React, Ruby and Rails, Computer science fundamentals & programming skills.

VIEW DETAILS

Upgrade FSWD to include Python, Data Science, AI Application, TypeScript and more.

3 Courses

FEWD

HTML
CSS
JavaScript

Front-end Web Development

Learn front-end development with HTML, CSS, JavaScript, and jQuery. Computer science fundamentals & programming skills.

VIEW DETAILS

2 Courses

BEWD

Database
API
Testing

Back-end Web Development

Learn back-end development with Ruby and Rails, M-V-C. Computer science fundamentals with practical programming skills.

VIEW DETAILS

Join the upcoming Cohort and learn web development online!


[8]ページ先頭

©2009-2025 Movatter.jp