【问题标题】:Getting the error text in an XMLHttpRequest error call back在 XMLHttpRequest 错误回调中获取错误文本
【发布时间】:2019-11-13 13:40:43
【问题描述】:

鉴于这个小sn-p代码:

function getPage () {
        var xhttp = new XMLHttpRequest();
        xhttp.addEventListener("error", getFailed);
        xhttp.open("GET", "http://nonexistentserver.com", true);
        xhttp.send();
        }

function getFailed(msg) {
    // I get an ProgressEvent object which doesn't have any text properties?
        }

当它运行时,确实调用了 getFailed() 回调,但我找不到任何关于如何确定错误的信息。当我搜索信息时,我只能找到 HTML 错误(如 404)和有关导致错误的错误报告。如何获取错误回调中可用的失败信息?

【问题讨论】:

标签: javascript xmlhttprequest


【解决方案1】:

在您的情况下,似乎无法获取错误信息。有一些显示请求状态的属性:XMLHttpRequest.status、XMLHttpRequest.statusText 和 XMLHttpRequest.responseText。但在这种情况下,它们在这里都不起作用(只有 XMLHttpRequest.status 显示“0”)。刚刚发生错误时调用 XMLHttpRequest 的错误事件。它不会发送有关错误的任何信息。我希望这些对您有所帮助:XMLHttpRequestXMLHttpRequest Properties

【讨论】:

    【解决方案2】:

    您可以尝试使用onprogress 事件并处理状态码,如下所示:

    var xhr = new XMLHttpRequest;
    xhr.onprogress = function () {
      console.log(xhr.status); //404 will be printed on console
    };
    
    xhr.open('GET', '/noexists');
    xhr.send(); 
    

    【讨论】:

    • 我的问题是我已经知道如何捕获 404 错误。我想捕获未找到服务器本身的错误(例如 DNS 或网络错误。)
    • 这样使用xhr.status会返回错误码,你可以按照Client Error Responsesdeveloper.mozilla.org/en-US/docs/Web/HTTP/…Server Error Responsesdeveloper.mozilla.org/en-US/docs/Web/HTTP/…处理它
    • 同样,这些是服务器返回的错误。我的问题涉及无法联系服务器的错误。
    • 对不起,javascriptXMLHttpRequest 你只会得到http协议级别的错误代码,我认为你需要一个接近网络级别的协议才能得到它
    猜你喜欢
    • 2017-12-14
    • 1970-01-01
    • 2016-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-03
    • 2022-01-19
    • 2021-03-26
    相关资源
    最近更新 更多