Reputation: 13933
I am using Grape on Rails. Although I am unable to set CORS for it.
The rack-cors gem explains how to set it for "Rails" in application.rb. Although does not show how to enable it for Grape on Rails.
Any thoughts ?
Upvotes: 1
Views: 2182
Reputation: 1226
A few easy steps and we'll be ready to go!
Add the following to your Gemfile and bundle install:
gem 'rack-cors', :require => 'rack/cors'
Add your API module to config/application.rb and configure your Rack-CORS Middleware:
module MyAppRails
class Application < Rails::Application
config.middleware.use Rack::Cors do
allow do
origins "*"
resource "*", headers: :any, methods: [:get, :post, :put, :delete, :options]
end
end
config.active_record.raise_in_transactional_callbacks = true
end
With origins "*"
, we specify that our API will accept HTTP requests from any domain in the whole wide internet.
With resource "*"
, we specify that a cross-origin request can access any of our resources (although we currently only have one––the resource for graduates).
We then specify that a cross-origin request using any HTTP method will be accepted––although, if you recall, we defined our Graduates class inside our API module to respond to only requests for all grads or just one grad. We can add the other HTTP methods later.
Upvotes: 3
Reputation: 23327
You can add headers manually, as suggested in one of grape issues: https://github.com/ruby-grape/grape/issues/170.
I would try to use the rack-cors middleware: either using it directly or wrapping it with a Grape Middleware (http://www.rubydoc.info/github/intridea/grape/Grape/Middleware/Base)
Upvotes: 0