GCDWebServer返回HTTPRequest状态为零,没有responseText

时间:2017-02-26 15:54:11

标签: cocoa xmlhttprequest gcdwebserver

我有以下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

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

1 个答案:

答案 0 :(得分:1)

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

Access-Control-Allow-Origin: *

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