GCDWebServer returns 没有响应文本的 HTTPRequest 状态为零

GCDWebServer returns HTTPRequest status zero with no responseText

我有以下 javascript 应用程序,它从运行在 OSX 应用程序上的 GCDWebServer 接收数据。

var HttpClient = function() {
        this.get = function(aUrl, aCallback) {
            var anHttpRequest = new XMLHttpRequest();
            anHttpRequest.open( "GET", aUrl, true );   
            anHttpRequest.onreadystatechange = function() { 
                if (anHttpRequest.readyState == 4 && anHttpRequest.status == 200) {
                    aCallback(anHttpRequest.responseText);
                    document.write (anHttpRequest.responseText);
                   }
                   else {
                    document.write ("Not Ok: ReadyState=" + anHttpRequest.readyState + " Status= " + anHttpRequest.status);
                   }
            }      
            anHttpRequest.send( null );
        }
    }

    var client = new HttpClient();
    client.get('http://xxx.xxx.x.xx:8080?var=param', function(response) {
        document.write ("Success"); 
    });

Cocoa 应用程序运行以下代码:

[webServer addDefaultHandlerForMethod:@"GET"
                             requestClass:[GCDWebServerRequest class]
                        asyncProcessBlock:^(GCDWebServerRequest* request, GCDWebServerCompletionBlock completionBlock) {

                            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                                GCDWebServerDataResponse* response = [GCDWebServerDataResponse responseWithJSONObject:dict];
                                completionBlock(response);
                            });

我总是得到 anHttpRequest.readyState = 4 和 anHttpRequest.status = 0。anHttpRequest.responseText 是空的。

但是,当我打开任何浏览器并输入 http://xxx.xxx.x.xx:8080?var=param 时,我得到了正确的结果。所以服务器正在正确发送数据。

这是来自 GCDWebServer 的日志

[DEBUG] Did open connection on socket 13
[DEBUG] Did connect
[DEBUG] Connection received 312 bytes on socket 13
[DEBUG] Connection on socket 13 preflighting request "GET /" with 312 bytes body
[DEBUG] Connection on socket 13 processing request "GET /" with 312 bytes body
[DEBUG] Connection sent 175 bytes on socket 13
[DEBUG] Connection sent 107 bytes on socket 13
[DEBUG] Did close connection on socket 13
[VERBOSE] [xxx.xxx.x.xx:8080] xxx.xxx.x.xx:52401 200 "GET /" (312 | 282)
[DEBUG] Did disconnect

有什么想法吗? 提前致谢。

这不是您的 GCDWebServer 的问题,而只是一个 CORS 问题。如果您从 curl 之类的东西向您的服务器发出相同的请求,那么您将看到正确的 200 HTTP 状态。要从浏览器获得正确的响应,您需要让您的服务器发送以下 header:

Access-Control-Allow-Origin: *

这告诉浏览器它可以将从您的服务器获得的完整响应传回给发起请求的JavaScript。如果没有该响应 header,浏览器基本上会丢弃它收到的所有数据,并且应该在浏览器的控制台中打印出一条错误消息。