Blog>
Snippets

Basic GET Request with Cross-Origin Request

Use the Fetch API to make a simple GET request to a cross-origin API endpoint and process the JSON response.
// This function makes a GET request to a cross-origin API endpoint
function fetchCrossOriginData(url) {
  // Use the Fetch API to make the GET request
  fetch(url)
    .then(response => {
      // Check if the response status is OK (status code 200)
      if (!response.ok) {
        throw new Error('Network response was not ok.');
      }
      // Parse the JSON response
      return response.json();
    })
    .then(data => {
      // Process the JSON data
      console.log('Data retrieved:', data);
    })
    .catch(error => {
      // Handle any errors that occurred during the fetch
      console.error('Fetch error:', error);
    });
}

// Example usage: fetchCrossOriginData('https://api.example.com/data');
This function `fetchCrossOriginData` takes a URL as an argument and uses the Fetch API to make a GET request to that URL. It then processes the response to ensure it's OK and parses the JSON body. Finally, the function logs the data or any errors that occurred during the request.