Blog>
Snippets

Handling CORS Errors in Javascript

Provide an example of how to catch and handle CORS (Cross-Origin Resource Sharing) errors when they occur during Fetch requests.
fetch('https://some-external-api.com/data')
  .then(response => {
    // Check if the response is ok (status in the range 200-299)
    if (!response.ok) {
      // If not, throw an error
      throw new Error('Network response was not ok');
    }
    return response.json(); // Try to parse JSON
  })
  .then(data => {
    // handle your data here
    console.log(data);
  })
  .catch(error => {
    if (error.name === 'TypeError' && error.message.includes('Network')) {
      console.error('A network error occurred. This could be a CORS issue or a dropped connection. Error:', error);
    } else {
      console.error('An unknown error occurred:', error);
    }
  });
This snippet fetches data from an external API and handles possible CORS errors. It first checks for a successful response, then tries to parse JSON. If an error occurs, it catches and logs details about the error, including mentioning of CORS if relevant.