How to Detect Cross Origin (CORS) Error vs. Other Types of Errors for XMLHttpRequest() in Javascript

后端 未结 5 1603
说谎
说谎 2020-11-30 00:33

I\'m trying to detect when an XMLHttpRequest() fails due to a Cross Origin Error as opposed to a bad request. For example:

    ajaxObj=new XMLHttpRequest()
         


        
5条回答
  •  有刺的猬
    2020-11-30 00:43

    Maybe in case it helps anyone... one other way to handle difference between cors and network error... can work with chrome or firefox... (not perfect solution though)

    var external = 'your url';
    
    if (window.fetch) {
        // must be chrome or firefox which have native fetch
        fetch(external, {'mode':'no-cors'})
            .then(function () {
                // external is reachable; but failed due to cors
                // fetch will pass though if it's a cors error
            })
            .catch(function () {
                // external is _not_ reachable
            });
    } else {
        // must be non-updated safari or older IE...
        // I don't know how to find error type in this case
    }
    

提交回复
热议问题