CORS请求:如果状态为0,如何读取服务器响应

时间:2017-06-21 09:39:22

标签: javascript cors

我使用以下代码通过Javascript向服务器执行请求:

<script>
    (function() {
        function createCORSRequest(method, url) {
            var xhr = new XMLHttpRequest();
            if ("withCredentials" in xhr) {
                xhr.open(method, url, true);
            } else if (typeof XDomainRequest != "undefined") {
                xhr = new XDomainRequest();
                xhr.open(method, url);
            } else {
                xhr = null;
            }
            return xhr;
        }
        var request = createCORSRequest("get", "http://remoteurltobecalled");
        if (request) {
            request.onload = function () {
                if (request.readyState == request.DONE) {
                    if (request.status == 200) {
                        var text = request.responseText;
                        alert(text);
                    }
                } 
            }

            request.onerror = function () {
                alert('status:'+request.status);
                alert('statusText: '+request.statusText);
                alert('responseText: ' + request.responseText);
                alert('responseBody: ' + request.responseBody);
                alert('Woops, there was an error making the request.');
            };

            var response=request.send();
        }
    })();
</script>

使用Fiddler我可以看到来自服务器的响应是:

HTTP/1.1 200 OK
Date: Wed, 21 Jun 2017 09:20:55 GMT
Server: Apache/2.4.7 (Ubuntu)
Set-Cookie: JSESSIONID=9A78296BD30D8AA45C1B4DF467118309; Path=/PATHREQUESTED
Vary: Accept-Encoding
Content-Length: 19982
Keep-Alive: timeout=5, max=100
Connection: Keep-Alive
Content-Type: text/html;charset=ISO-8859-1

然后是回应的主体。

无论如何,javascript代码中的响应是错误的,状态为0,responseText和responseBody为空。我怎么能得到服务器提供的完整响应?这是一个CORS问题吗?

0 个答案:

没有答案