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

后端 未结 5 1649
说谎
说谎 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 01:08

    No, there is no way to tell the difference, according the W3C Spec.

    Here's how the CORS specification specifies the simple cross-origin request procedure:

    Apply the make a request steps and observe the request rules below while making the request.

    If the manual redirect flag is unset and the response has an HTTP status code of 301, 302, 303, 307, or 308: Apply the redirect steps.

    If the end user cancels the request: Apply the abort steps.

    If there is a network error: In case of DNS errors, TLS negotiation failure, or other type of network errors, apply the network error steps. Do not request any kind of end user interaction...

    Otherwise: Perform a resource sharing check. If it returns fail, apply the network error steps...

    In the case of either a failed network connection or a failed CORS exchange, the network error steps are applied, so there is literally no way to distinguish between the two cases.

    Why? One benefit is that it prevents an attacker from inspecting the network topology of a LAN. For example, a malicious Web page script could find the IP address of your router by requesting its HTTP interface and therefore learn a few things about your network topology (e.g., how big your private IP block is, /8 or /16). Since your router doesn't (or shouldn't) send CORS headers, the script learns absolutely nothing.

提交回复
热议问题