JavaScript Fetch API
The JavaScript Fetch API provides a powerful interface for fetching resources asynchronously across the network. It is built into most modern browsers and is used to perform HTTP requests, allowing developers to easily retrieve data from APIs or other online resources.
Basic Usage
To perform a GET request and retrieve data from an endpoint, you can use the Fetch API as follows:
fetch('https://api.example.com/data') .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error('Error:', error));
Handling Responses
The Fetch API returns a Promise that resolves to the Response object representing the response to the request. This object contains the status code, headers, and the body of the response.
Differences Between fetch
and XMLHttpRequest
While fetch
is the modern way to make HTTP requests in JavaScript, XMLHttpRequest
was the previous standard. fetch
provides a more powerful and flexible feature set and returns Promises, making it easier to work with asynchronous operations.
Error Handling
Error handling with Fetch is done using .catch()
for network errors, but you also need to check the response status code to handle HTTP errors:
fetch('https://api.example.com/data') .then(response => { if (!response.ok) { throw new Error('Network response was not ok ' + response.statusText); } return response.json(); }) .then(data => console.log(data)) .catch(error => console.error('Error:', error));
Advanced Usage
For more advanced scenarios, such as sending headers or a request body, the Fetch API allows you to specify an options object:
fetch('https://api.example.com/data', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ key: 'value' }),}).then(response => response.json()).then(data => console.log(data)).catch(error => console.error('Error:', error));
The Fetch API is a cornerstone of modern web development, enabling developers to interact with APIs and other web services in a simple and efficient manner.
Was this helpful?
Related Documentation
Supabase collect vs fetch comparison
Explore the technical nuances between collect and fetch methods in Supabase for efficient data retrieval.
Explore efficient data retrieval with Supabase fetch. Learn best practices for querying and managing data.