Cloudfront CORS issue serving fonts on Rails application

后端 未结 5 2052
栀梦
栀梦 2021-01-31 10:07

I keep receiving this error message from the console when visiting my website:

font from origin \'https://xxx.cloudfront.net\' has been blocked from loading by C         


        
5条回答
  •  星月不相逢
    2021-01-31 10:32

    I just had the same issue and managed to solve it.

    You've correctly told Cloudfront to allow those headers, but you haven't added those headers to where Cloudfront gets the font. Yes, your origin headers are allowed, but Heroku isn't sending those headers with the font anyway.

    To fix this, you'll need to get the proper CORS headers added to the font on Heroku. Luckily, this is pretty easy.

    First, add the rack/cors gem to your project. https://github.com/cyu/rack-cors

    Next, configure your Rack server to load and configure CORS for any assets it serves. Add the following after your application preloads in config.ru

    require 'rack/cors'
    use Rack::Cors do
      allow do
        origins '*'
    
        resource '/cors',
          :headers => :any,
          :methods => [:post],
          :credentials => true,
          :max_age => 0
    
        resource '*',
          :headers => :any,
          :methods => [:get, :post, :delete, :put, :patch, :options, :head],
          :max_age => 0
        end
      end
    

    This sets any resources returned from Heroku to have the proper CORS headers applied. You can restrict the application of headers depending on your file and security needs.

    Once deployed, go into Cloudfront and begin an invalidation on anything that was previously giving you a CORS permission error. Now when Cloudfront loads a fresh copy from Heroku, it will have the correct headers, and Cloudfront will pass those headers on to the client as previously configured with your Origin permissions.

    To make sure you're serving the proper headers from your server, you can use the following curl command to validate your headers: curl -I -s -X GET -H "Origin: www.yoursite.com" http://www.yoursite.dev:5000/assets/fonts/myfont.svg

    You should see the following headers returned:

    Access-Control-Allow-Origin: www.yoursite.com
    Access-Control-Allow-Methods: GET, POST, DELETE, PUT, PATCH, OPTIONS, HEAD
    Access-Control-Max-Age: 0
    Access-Control-Allow-Credentials: true
    

提交回复
热议问题