I have a Rails app running in Heroku, and a html file using Jquery Mobile.
The Rails app returns JSON data (using RABL), that my mobile app is suppose to pick up and show.
This is what I'm doing, I'm feeding the contents of the response to a listview. Pretty simple. If I use Chrome, the console shows the error Origin null is not allowed by Access-Control-Allow-Origin. IF I try on Firefox, there's no error on the console, but the data is not shown either, not even the alert triggers.
function getBuses(){
$('#content').append("<ul id='bus_list' data-role='listview' data-inset='true'</ul>")
$('#content').trigger("create");
//Se llama a la API para retornar todos los buses
$.getJSON('http://someapp.herokuapp.com/buses.json', function(data)
{
$.each(data, function(key, value)
{
alert(key + ":" + value);
$('#bus_list').append('<li id="'+bus.id+'">'+bus.numero_de_linea+'<li/>');
});
});
$('#bus_list').listview("refresh");
}
This is what the server responds:
[{"id":7,"numero_de_linea":"604"}]
I've reading on Access-Control-Allow-Origin for a while now, but I'm not sure what I have to do, should I change something in my server? I'm trying this html file on my browser, but it's not working on my phone either.
I have set $.support.cors
and $.mobile.allowCrossDomainPages = true;
to true when mobileinit
runs.
Any information on what to do next, would be greatly appreciated.
EDIT: If you are working with RABL, remember to set the variable enable_json_callback to true in the initializer. You have to enable this thing from both sides.
Since the header is currently set to allow access only from https://yoursite.com , the browser will block access to the resource and you will see an error in your console. Now, to fix this, change the headers to this: res. setHeader("Access-Control-Allow-Origin", "*");
Handling cross-origin resource requests with credentials Then the browser will permit the requesting website to read the response, because the Access-Control-Allow-Credentials response header is set to true . Otherwise, the browser will not allow access to the response.
To correct this problem on the client side, ensure that the credentials flag's value is false when issuing your CORS request. If the request is being issued using XMLHttpRequest , make sure you're not setting withCredentials to true . If using Server-sent events, make sure EventSource.
The 'Access-Control-Allow-Origin' header is insecure when set to '*' or null, as it allows any domain to perform cross-domain requests and read responses.
In Rails 4 the command after_filter
has been changed to after_action
so the finished code in the top of the controller should be:
after_action :set_access_control_headers
def set_access_control_headers
headers['Access-Control-Allow-Origin'] = "*"
headers['Access-Control-Request-Method'] = %w{GET POST OPTIONS}.join(",")
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With