无法在纯js中处理net::ERR_CONNECTION_REFUSED

cannot handle net::ERR_CONNECTION_REFUSED in pure js

本文关键字:ERR CONNECTION REFUSED net 处理 js      更新时间:2024-04-19

我使用纯js(不带JQuery)向服务器发送XMLHttpRequest请求。

        var _xhr = new XMLHttpRequest();
        _xhr.open(type, url);
        _xhr.setRequestHeader('Content-Type', 'application/json');
        _xhr.responseType = 'json';
        _xhr.onload = function () {
            if (_xhr.status === 200) {
                var _json = _xhr.response;
                if (typeof _json == 'string')
                    _json = JSON.parse(_json);
                success(_json);
            } else {
                error(_xhr);
            }
        };
        _xhr.onerror = function(){
            console.log('fail');
        };
        try {
            _xhr.send(_to_send);
        } catch (e){
            options.error(_xhr);
        }

当我发送请求时,它失败了(这是可以的),我得到了一个错误,但我无法处理它。xhr.onerror将消息打印到控制台,但我也得到了OPTIONS url net::ERR_CONNECTION_REFUSED。如何在控制台中避免此消息?

此外,我使用window.onerror来处理所有错误,但我无法处理此OPTIONS url net::ERR_CONNECTION_REFUSED

这对我有效:

// Watch for net::ERR_CONNECTION_REFUSED and other oddities.
_xhr.onreadystatechange = function() {
  if (_xhr.readyState == 4 && _xhr.status == 0) {
    console.log('OH NO!');
  }
};

这不仅限于net::ERR_CONNECTION_REFUSED,因为其他网络错误(例如net::ERR_network_CHANGEDnet::ERR_ADDRESS_UNREACHABLEnet::ERR_TIMED_OUT)可能会以这种方式"捕获"。我无法在_xhr对象中的任何位置找到这些错误消息,因此通过编程确定具体发生了哪个网络错误是不可靠的。

控制台中显示的错误是无法避免的。就像您请求一个不存在的文件一样,无论您是否处理了错误,您都会在控制台中得到一个404