3

我使用纯 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

4

2 回答 2

1

这对我有用:

// 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 对象中找到这些错误消息,因此以编程方式决定具体发生了哪个网络错误是不可靠的。

于 2016-11-02T20:25:22.163 回答
0

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

于 2016-04-11T14:59:32.993 回答