3
我试图设置一个启用CORS的API,可以通过JavaScript访问。浏览器和AJAX响应CORS标头不同
我使用来测试代码是这样的:
$(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请求。
我已经启用CORS在我的nginx的配置
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
当我在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: *
不用说,我很困惑,为什么这是不工作,任何想法?
对,这样可以解释标题中的差异,但是我假设它返回403的原因是因为原始位置不被允许? – djlumley 2012-01-10 22:39:27
我不知道它为什么会返回403,但X-Powered-By标题让我觉得它来自于ruby应用程序。 – kolbyjack 2012-01-11 12:08:16