6

I'm trying to import a JS package hosted on a CDN using the new Rails 7 import maps feature. However, whenever my Rails project loads I get a CORS related error in this form:

Access to script at 'https://cdn.vender-application.com/package.js' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

My importmap.rb looks something like this:

pin "va_cdn", to: "https://cdn.vender-application.com/package.js"

I added the rack-cors gem along with a cors.rb file, however it had no effect. Example cors files:

  • I first tried with a general config/initializers/cors.rb:
Rails.application.config.middleware.insert_before 0, Rack::Cors do
  allow do
    origins '*'
    resource '*', headers: :any, methods: :any
  end
end
  • After that failed I tried being more specific as I've heard some services don't like an * Origin. I used http://127.0.0.1:3000 as that was the exact origin listed in the error message. I tried both with resource '*' and a more specific one:
Rails.application.config.middleware.insert_before 0, Rack::Cors do
  allow do
    origins 'http://127.0.0.1:3000'
    resource '/', headers: :any, methods: :any
    resource '/index', headers: :any, methods: :any
  end
end

I seems like it something specific to importmaps, since this code will successfully get the package:

<% content_for :head do %>
  <%= javascript_include_tag "https://cdn.vender-application.com/package.js" %>
<% end %>

I'd prefer to use the new recommended way of getting this package, rather than inlining the call.

James
  • 1,158
  • 4
  • 13
  • 23

0 Answers0