Frontend Development: Introduction to JavaScript Fetch API

Peter Jeon·2023년 6월 19일
0

Frontend Development

목록 보기
14/80
post-custom-banner

JavaScript Fetch API

The JavaScript Fetch API is a modern, promise-based system for making network requests. This API is superior to the outdated XMLHttpRequest, which is more complicated to use and doesn't provide the benefits of promises.

What is Fetch API?

What is Fetch API

The Fetch API is a simple and logical way to fetch resources asynchronously across a network. It will seem familiar to anyone who has used XMLHttpRequest, but the new API provides a more powerful and flexible feature set.

How to use Fetch API?

How to use Fetch API

fetch('https://api.example.com/data', {
  method: 'GET', 
  headers: {
    'Content-Type': 'application/json',
  }
})
.then(response => response.json())
.then(data => console.log(data))
.catch((error) => {
  console.error('Error:', error);
});

The fetch() function returns a Promise that resolves to the Response object representing the response to the request. This response could be success, failure, or anything else.

Error Handling in Fetch API

A common misconception is that fetch() will reject the promise if the HTTP status is an error. It's not true. fetch() will only reject the promise if there's a network error.

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('There has been a problem with your fetch operation:', error);
});

In the above example, we are checking the ok property of the Response object to check if the HTTP response status is in the successful range.

Fetch API Options

The fetch() function accepts two arguments: the path to the resource you want to fetch, and an options object.

fetch(url, options);

The options object can contain the following:

  • method: The request method, e.g., GET, POST.
  • headers: Any headers you want to add to your request.
  • body: The body data type must match "Content-Type" header.

And that's it! That's your introduction to the Fetch API in JavaScript. With it, you can make promise-based network requests in the browser and in Node.js.

profile
As a growing developer, I am continually expanding my skillset and knowledge, embracing new challenges and technologies
post-custom-banner

0개의 댓글