Rails 7 import map with javascript package from cdn throwing CORS error
Asked Answered
S

1

8

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.

Storz answered 23/6, 2022 at 7:16 Comment(1)
Could you add the details of the error you have? like the stacktrace.Chartist
S
0

Did you run bin/importmap pin for your package?

Importmaps get vendored locally and committed to your repo. It looks like you're trying to load it live from the CDN and I've never seen import map-rails used this way.

https://github.com/rails/importmap-rails#usage

And here's what my importmap.rb looks like.

pin "application", preload: true

pin "@hotwired/turbo-rails", to: "turbo.js"
pin "@hotwired/stimulus", to: "stimulus.min.js"
pin "@hotwired/stimulus-loading", to: "stimulus-loading.js"
pin "form-request-submit-polyfill" # @2.0.0
pin "@vimeo/player", to: "@vimeo--player.js" # @2.18.0
pin "js-cookie" # @3.0.1
pin "jcrop" # @3.0.1
pin "hammerjs" # @2.0.8
pin "@rails/request.js", to: "@rails--request.js.js" # @0.0.9

pin_all_from "app/javascript/lib", under: "lib"
pin_all_from "app/javascript/controllers", under: "controllers"
pin_all_from "app/javascript/helpers", under: "helpers"
pin_all_from "app/components", under: "components"
Scavenge answered 14/8, 2024 at 19:13 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.