Answer the question
In order to leave comments, you need to log in
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
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');
}
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question