Get rid of a 401 (unauthorized) ajax error in browser console

后端 未结 2 1497
刺人心
刺人心 2021-02-20 06:11

I\'m calling an api through javascript using a jQuery.ajax call. The api respond with 401 if the user is not authenticated and I want to ignore this error only for this call.

2条回答
  •  灰色年华
    2021-02-20 06:35

    I also ran into this issue and wanted to surpress the exception in the JavaScript console for HTTP 401 and 404 etc errors. I found this question and didn't see why the error() and statusCode() handlers didn't quiet the exception so i did my own digging into it.

    As far as i can tell it turns out that this is an issue with the native ajax XMLHttpRequest Object in the browser, not with jQuery. To prove this i used the following test code:

    function xhrTest(index) {
        var ajaxObjects = [
            $.ajaxSettings.xhr(), // what jquery returns
            new XMLHttpRequest()  // the native one in the browser
        ];
        var ajax = ajaxObjects[index];
        ajax.onreadystatechange = function() {console.log("xhrTest: state: " + ajax.readyState)};
        var errorHandler = function() {console.log("xhrTest: error");};
        ajax.onerror = errorHandler;
        ajax.onabort = errorHandler;
        ajax.open("GET", "/fileThatDoesNotExist", true);
        ajax.send();    
    }
    

    Note that when calling this (i did it from the JavaScript console) with either xhrTest(0) or xhrTest(1), which bypasses jQuery, that the results are the same:

    same results whether jQuery is used or not

提交回复
热议问题