我有以下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");
    });


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

[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状态。为了从浏览器获得正确的响应,您将需要服务器发送以下标头:

Access-Control-Allow-Origin: *


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

10-06 02:38