簡體   English   中英

在純js中無法處理net :: ERR_CONNECTION_REFUSED

[英]cannot handle net::ERR_CONNECTION_REFUSED in pure js

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM