How to Fetch Data from any API in JavaScript

Fetching data from an API in JavaScript is commonly done using the fetch API or libraries like Axios. Here’s a simple example of how to use both methods:

Using the Fetch API

The fetch API is a modern and widely supported way to make HTTP requests in JavaScript. It returns a promise that resolves to the response of the request.

Basic Example:

// URL of the API
const apiUrl = 'https://api.example.com/data'; // Fetch data from the API
fetch(apiUrl) .then(response => { if (!response.ok) { throw new Error('Network response was not ok ' + response.statusText); } return response.json(); // parse the JSON from the response }) .then(data => { console.log(data); // Handle the JSON data }) .catch(error => { console.error('There has been a problem with your fetch operation:', error); });
Enter fullscreen mode
Exit fullscreen mode

Using Async/Await with Fetch

Using async and await makes the code look cleaner and more readable.

// URL of the API
const apiUrl = 'https://api.example.com/data'; // Function to fetch data
async function fetchData() { try { const response = await fetch(apiUrl); if (!response.ok) { throw new Error('Network response was not ok ' + response.statusText); } const data = await response.json(); // parse the JSON from the response console.log(data); // Handle the JSON data } catch (error) { console.error('There has been a problem with your fetch operation:', error); }
} // Call the function
fetchData();
Enter fullscreen mode
Exit fullscreen mode

Summary

  • Use the fetch API for a built-in, promise-based approach to make HTTP requests.

Discover more from Coursity

Subscribe to get the latest posts sent to your email.

Leave a Comment

Your email address will not be published. Required fields are marked *

Discover more from Coursity

Subscribe now to keep reading and get access to the full archive.

Continue reading

Scroll to Top
Aantal domeinen te hosten bij getphphost get a host. Tag archives : cry macho 2021 fmovies.