» Quick Introduction to JavaScript » 2. Advanced » 2.5 Fetch

Fetch

The global fetch() method starts the process of fetching a resource from the network, returning a promise that is fulfilled once the response is available.

// URL of the API endpoint you want to fetch data from
const apiUrl = 'https://jsonplaceholder.typicode.com/todos/1';

// Using fetch to make a GET request
fetch(apiUrl)
  .then(response => {
    // Check if the request was successful (status code 200-299)
    if (!response.ok) {
      throw new Error(`HTTP error! Status: ${response.status}`);
    }
    
    // Parse the response as JSON
    return response.json();
  })
  .then(data => {
    // Handle the data from the response
    console.log('Data:', data);
  })
  .catch(error => {
    // Handle errors that may occur during the fetch operation
    console.error('Fetch error:', error);
  });

The async/await version for this example looks like this:

async function fetchData() {
  // URL of the API endpoint you want to fetch data from
  const apiUrl = 'https://jsonplaceholder.typicode.com/todos/1';

  try {
    // Using await to make a GET request with fetch
    const response = await fetch(apiUrl);

    // Check if the request was successful (status code 200-299)
    if (!response.ok) {
      throw new Error(`HTTP error! Status: ${response.status}`);
    }

    // Parse the response as JSON
    const data = await response.json();

    // Handle the data from the response
    console.log('Data:', data);
  } catch (error) {
    // Handle errors that may occur during the fetch operation
    console.error('Fetch error:', error);
  }
}

// Call the async function to execute the asynchronous operation
fetchData();

If you don't care about errors and just want to put it really simple, do as below then:

fetch('https://jsonplaceholder.typicode.com/todos/1')
  .then(response => response.json())
  .then(json => console.log(json))