M
M
MikUrrey2022-01-05 16:01:51
JavaScript
MikUrrey, 2022-01-05 16:01:51

JS fetch(): how to distinguish CORS error from others?

You need to catch the CORS exception and attach a unique handler to it in the UI.
Until I found a way myself, the errors flying in catch are extremely vague: TypeError: Failed to fetch , regardless of the reason. However, the console somehow distinguishes between errors and displays the notification has been blocked by CORS policy or This content should also be served over HTTPS. So is there a way?
PS yes, I would also like to display a unique notification for an attempt to get unsafe content from a safe resource.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
MikUrrey, 2022-01-05
@MikUrrey

As it turned out, for security reasons, browsers do not share with web developers the reasons for blocking requests, but with low accuracy and indirect evidence, the cause of the error can still be determined:

const url = 'some url';
try {
      const response = await fetch(url);
      //.....
} catch {
      if (url.startsWith('http:')) {
        console.log(`It's may be a mixed content error`);
      } else {
        try {
          await fetch(url, {'mode':'no-cors'}); //если ресурс доступен, то ошибки не будет
          console.log(`It's may be a CORS error`);
        } catch {
          console.log('Other error');
        }
      }
}

When applying this solution anywhere, keep in mind that this method does not give a 100% accurate answer whether the error is CORS or not.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question