Reputation: 5411
I'm trying to use a google font on my rails app, but I'm getting this message on my console and the font is not loaded.
XMLHttpRequest cannot load http://fonts.googleapis.com/css?family=Open+Sans. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://pre.blabloo.com' is therefore not allowed access.
I got the same error on my localhost:3000. I add the following code to my application helper but I still getting the error.
after_filter :set_access_control_headers
def set_access_control_headers
headers['Access-Control-Allow-Origin'] = '*'
headers['Access-Control-Request-Method'] = '*'
end
or
after_filter :set_access_control_headers
def set_access_control_headers
headers['Access-Control-Allow-Origin'] = 'https://pre.blabloo.com'
headers['Access-Control-Request-Method'] = '*'
end
But nothing happens
Any help please.
UPDATE
I also tried the rack-cors gem like this:
On my config/application:
config.middleware.insert_before "ActionDispatch::Static", "Rack::Cors" do
allow do
origins 'http://localhost:3000'
resource '*', :headers => :any, :methods => [:get, :post, :options]
end
end
But it does not work. Now I have another cross domaing problem with youtube.
Upvotes: 4
Views: 3858
Reputation: 5411
I can't solve the problem with any configuration of 'Access-Control-Allow-Origin', so I decide to upload the font to the server.
Thanks anyway for your help.
Upvotes: 0
Reputation: 1008
I would add it like this to your application.rb
config.action_dispatch.default_headers = {
'Access-Control-Allow-Origin' => '*',
'Access-Control-Request-Method' => %w{GET POST OPTIONS}.join(",") # or whatever else you would like to allow
}
works for me.
Upvotes: 1
Reputation: 8518
I've tried to reproduce your problem and it was working for me with the following layout and stylesheet_link_tag
:
<!DOCTYPE html>
<html>
<head>
<title>SoAccessControl</title>
<%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track' => true %>
<%= stylesheet_link_tag 'application', 'http://fonts.googleapis.com/css?family=Open+Sans' %>
<%= javascript_include_tag 'application', 'data-turbolinks-track' => true %>
<%= csrf_meta_tags %>
</head>
<body>
<%= yield %>
</body>
</html>
I've set the right font-family
in my stylesheet and it worked. After that, I tried to set the headers. And that worked to:
class ApplicationController < ActionController::Base
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :exception
after_filter :set_cors
def set_cors
headers['Access-Control-Allow-Origin'] = 'https://example.com'
headers['Access-Control-Request-Method'] = '*'
end
end
Here the verification:
Upvotes: 0