I’m trying to setup a CORS enabled API that I can access via JavaScript.
The code I’m using to test is this:
$(function(){
get = function(url_fragment)
{
$.ajax({
url: 'my_api',
dataType: 'json',
cache: false,
success: function(data)
{
alert('success');
},
error: function(data)
{
alert('failure');
}
})
}
get('');
});
It’s a fairly simple AJAX request.
I’ve enabled CORS in my nginx config
add_header Access-Control-Allow-Origin *;
And when visiting the API in my browser, firebug shows the expected headers
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
When I view the XHR request in firebug the CORS header isn’t present:
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
I do receieve the correct headers when using 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: *
Needless to say, I’m confused as to why this isn’t working, any ideas?
add_header only works with a new status codes (200, 204, 301, 302 or 304). The response missing the header is a 403, so add_header won’t work. The third party headers more module is more flexible, and can add headers for any status code.