0

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

有任何想法吗?提前致谢。

4

1 回答 1

1

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

Access-Control-Allow-Origin: *

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

于 2017-02-26T16:28:30.323 回答