预检响应中的Access-Control-Allow-Origin不支持跨域访问

我正在尝试使用AJAX发送CORS请求到nodeJS服务器。 我想返回一些JSON数据。 我在网上发现了大量的教程,都说同样的事情,我已经尝试过,但我不能得到这个工作。 这是AJAX请求:

$.ajax({ url: "http://some.other.url.com:8880", type: "GET", crossDomain: true, contentType: 'application/json' }).then(function(response) { $scope.allData = jQuery.parseJSON( response ); console.log($scope.allData); }).fail(function(response) { }); 

这里是服务器上的代码:

 var path = url.parse(req.url).pathname, match = router.match(path), rescode; console.log("---: " + req.method); if (req.method === 'OPTIONS') { var headers = {}; headers["Access-Control-Allow-Origin"] = "*"; headers["Access-Control-Allow-Methods"] = "POST, GET, PUT, DELETE, OPTIONS"; headers["Access-Control-Allow-Credentials"] = false; headers["Access-Control-Max-Age"] = '86400'; // 24 hours headers["Access-Control-Allow-Headers"] = "X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept"; res.writeHead(200, headers); return res.end(); } 

我也试过没有返回res.end()即没有返回OPTIONS预检请求,这也不起作用。

– 编辑 – 这是控制台中的实际错误信息:

 Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://other.domain.com:8880/. This can be fixed by moving the resource to the same domain or enabling CORS. 

服务器正在获取请求。 OPTIONS和GET请求都会触发服务器并被响应。 事实上,在控制台loginAJAX请求的页面,我可以点击CORS错误并查看响应,这是正确的数据。 但我似乎无法让JavaScript继续。

对于.done.then ,他们似乎可以互换。 或者至less,在这个例子中, .fail.fail工作得很好。

您在OPTIONS预检响应中正确设置了CORS标题,但是您还需要在实际的GET响应中设置Access-Control-Allow-Origin (或者是您的出处或* )。 无论是否有预检响应,GET响应都应该使用相同的CORS头进行响应。 这意味着它必须发送适当的CORS头,但是除了Access-Control-Allow-Origin以外,不需要发送任何东西。 (如果涉及非简单动词或头文件等其他非简单组件,它们将被允许或被拒绝;实际的GET响应不需要担心。

启用CORS站点有一个CORStesting工具来帮助您查看您指定的请求中涉及的标头。 我已经使用该工具来设置类似于您的情况的testing (使用非简单的Content-Type标头进行GET)。 如果我们检查一下这个testing的结果(小心 – 这些步骤显示的有点乱,但是都在那里),我们看到一个预检反应:

 Access-Control-Allow-Methods: POST, GET, PUT, DELETE, OPTIONS ... Access-Control-Allow-Origin: http://client.cors-api.appspot.com Access-Control-Allow-Headers: X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept 

最后的CORS回应:

 Content-Length: 0 Content-Type: application/json Access-Control-Allow-Origin: http://client.cors-api.appspot.com Cache-Control: no-cache 

正如你所看到的,GET响应也有一个Access-Control-Allow-Origin标题,没有其他的CORS标题。 如果您还有其他不确定因素,请随意调整该工具上的设置,以运行各种其他testing用例。