我正在尝试设置一个支持CORS的API,我可以通过JavaScript访问它。
我用来测试的代码是:
$(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请求。
我在我的nginx配置中启用了CORS
add_header Access-Control-Allow-Origin *;
在浏览器中访问API时,firebug会显示预期的标题
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
当我在firebug中查看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: *
毋庸置疑,我很困惑为什么这不起作用,有什么想法?
答案 0 :(得分:4)
add_header仅适用于新的状态代码(200,204,301,302或304)。缺少标头的响应是403,因此add_header将不起作用。第三方headers more模块更灵活,可以为任何状态代码添加标头。