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

后端 未结 5 1640
说谎
说谎 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

    Surprisingly you can do that for images (and maybe there is a similar solution for other particular content types). The trick is that does apparently not regard CORS, therefore statement "url fails to load by XHR && url succeeds to load by img src" implies that the URL works but is CORS blocked.

    This definitely does not help in all cases, but in some cases (e.g. utility detecting if you're properly passing CORS) it may do the trick. For example I wanted to fire a a warning in console if my app (separate frontend and backend) is installed with correctly configured URL of backend and wrongly configured CORS on server, so this was perfectly enough for me as I can serve an image to test it on.

    function testCors(url) {
        var myRequest = new XMLHttpRequest();
        myRequest.open('GET', url, true);
        myRequest.onreadystatechange = () => {
            if (myRequest.readyState !== 4) {
                return;
            }
            if (myRequest.status === 200) {
                console.log(url, 'ok');
            } else {
                var myImage = document.createElement('img');
                myImage.onerror = (...args) => {console.log(url, 'other type of error', args);}
                myImage.onload = () => {console.log(url, 'image exists but cors blocked');}
                myImage.src = url;
                console.log(url, 'Image not found');
            }
        };
        myRequest.send();
    }
    

提交回复
热议问题