浏览器和AJAX响应CORS标题不同

我正在尝试设置一个可以通过JavaScript访问的启用CORS的API。

我用来testing的代码是这样的:

$(function(){ get = function(url_fragment) { $.ajax({ url: 'my_api', dataType: 'json', cache: false, success: function(data) { alert('success'); }, error: function(data) { alert('failure'); } }) } get(''); }); 

这是一个相当简单的AJAX请求。

我在我的nginxconfiguration中启用了CORS

 add_header Access-Control-Allow-Origin *; 

当在浏览器中访问API时,萤火虫显示预期的标题

 Access-Control-Allow-Origin * Connection keep-alive Content-Length 59 Content-Type application/json;charset=utf-8 Server nginx/1.0.11 + Phusion Passenger 3.0.11 (mod_rails/mod_rack) Status 200 X-Frame-Options sameorigin X-Powered-By Phusion Passenger (mod_rails/mod_rack) 3.0.11 X-XSS-Protection 1; mode=block 

当我在萤火虫中查看XHR请求时,CORS头不存在:

 Connection keep-alive Content-Encoding gzip Content-Type text/plain Server nginx/1.0.11 + Phusion Passenger 3.0.11 (mod_rails/mod_rack) Status 403 Transfer-Encoding chunked X-Frame-Options sameorigin X-Powered-By Phusion Passenger (mod_rails/mod_rack) 3.0.11 

使用curl时,我确实接受了正确的标题

 $ curl -i my_api HTTP/1.1 200 OK Content-Type: application/json;charset=utf-8 Connection: keep-alive Status: 200 X-Powered-By: Phusion Passenger (mod_rails/mod_rack) 3.0.11 X-Frame-Options: sameorigin X-XSS-Protection: 1; mode=block Content-Length: 61 Server: nginx/1.0.11 + Phusion Passenger 3.0.11 (mod_rails/mod_rack) Access-Control-Allow-Origin: * 

不用说,我很困惑,为什么这不起作用,有什么想法?

add_header只能使用新的状态码( 200,204,301,302或304)。 缺少标题的响应是403,所以add_header将不起作用。 第三方头多模块更灵活,可以为任何状态码添加头文件。