2

我正在使用 CORS 进行跨域调用。我的问题是我需要XDomainRequest在 IE 中处理 404 错误。

XDomainRequest我只能找到onerror处理所有错误事件的事件,但在我的要求中,我需要显示 404 错误情况的空占位符图像(API 不为此提供空的 200 响应,但使用 404)但不管其他错误。

这是请求网址:

http://photorankapi-a.akamaihd.net/streams/1537083805/media/photorank?auth_token=11ff75db4075b453ac4a21146a210e347479b26b67b1a396d9e29705150daa0d&version=v2.1

在其他浏览器中,我使用XMLHttpRequestandreq.status code == 404来获取responseText

{"metadata":{"code":404,"message":"Not Found","version":"v2.1"}}

但是当我试图从 req.onerror(below) 中获取 responseText 时,我只能得到空字符串,所以我无法区分 404 和其他错误。

部分代码如下所示:

xdr: function (url, method, data, callback, errback) {
    var req;
    if(typeof XDomainRequest !== "undefined") {
        req = new XDomainRequest();
        req.open(method, url);
        req.onerror = function() {
            // I want to handle specific 404 error here
            callback(req.responseText);
        };
        req.onload = function() {
            callback(req.responseText);
        };
        req.send(data);
    } else if( typeof XMLHttpRequest !== "undefined") {
        req = new XMLHttpRequest();
        if('withCredentials' in req) {
            req.open(method, url, true);
            req.onerror = errback;
            req.onreadystatechange = function() {
                if (req.readyState === 4) {
                    if ((req.status >= 200 && req.status < 400) || req.status ==404 ) {
                        callback(req.responseText);
                    } else {
                        errback(new Error('Response returned with non-OK status'));
                    }
                }
            };
            req.send(data);
        }
    } else {
        errback(new Error('CORS not supported'));
    }
}

XMLHttpRequest 工作正常,所有其他浏览器都在工作,除了在 IE 中。

4

1 回答 1

2

不幸的是,XDomainRequest 对象不提供访问响应 HTTP 状态代码的方法。您可以在 XDR 实例上访问的唯一属性是:constructor、、、contentTyperesponseTexttimeout唯一的方法是:abort()open()send()。最重要的是,错误处理程序甚至没有传递任何参数。

于 2014-05-08T23:28:27.937 回答