Catching an Access-Control-Allow-Origin error in JavaScript

前端 未结 2 1139
有刺的猬
有刺的猬 2020-11-28 16:18

I wrote a function that keeps returning an Access-Control-Allow-Origin error. This is actually fine for me; I don\'t want to fix this. I just want to catch

相关标签:
2条回答
  • 2020-11-28 17:04

    jquery version of above (sideshowbarker's) workaround for CORS error:

    let sURL = 'https://www.mocky.io/v2/5185415ba171ea3a00704eed';
    $.getJSON(sURL, function (json)
    {
        console.log('json from web-service ->', json);
    })
    .fail(function()
    {
        console.log("error - could not get json data from service");
    });
    
    0 讨论(0)
  • 2020-11-28 17:05

    While the browser itself will log a more-detailed error message to the console, you can’t access that message from your code. See https://bugs.chromium.org/p/chromium/issues/detail?id=118096#c5:

    The details of errors of XHRs and Fetch API are not exposed to JavaScript for security reasons.

    As far as the what specs actually require here, the Fetch spec is what defines the details of the “status message” to provide in case of an error — even if the XHR API is used instead of the Fetch API (the XHR spec references the Fetch spec). And for any network error or response blocked by the browser, the Fetch spec requires that the status message be “the empty byte sequence”:

    A network error is a response whose status is always 0, status message is always the empty byte sequence, header list is always empty, body is always null, and trailer is always empty.

    So all you can get back from any error object you can catch is “TypeError: Failed to fetch” or such.

    If you’re using XHR, the only means you have for handling an error is the onerror event handler:

    xhr.onerror = function() { console.log("Error occurred but I dunno what exactly.")}
    
    0 讨论(0)
提交回复
热议问题