CORS issue using Grape and Heroku APIs

I have a read-only API and it works well locally with Vagrant setup. In my Heroku application, every API request is rejected due to a CORS error: the "No" Access-Control-Allow-Origin header is present on the requested resource. Therefore, the original "null" does not have access. "

In my base API class, I have the following to set the headers:

module API class Base < Grape::API before do headers['Access-Control-Allow-Origin'] = '*' headers['Access-Control-Allow-Methods'] = 'GET, OPTIONS' headers['Access-Control-Request-Method'] = '*' headers['Access-Control-Allow-Headers'] = 'Origin, X-Requested-With, Content-Type, Accept, Authorization' end mount API::V1::Base end end 

I suspect that this before call does not start - if I use the puts statement inside it, this statement does not appear in my console with the rest of the output.

I'm at a loss. Hope someone has some experience with this. Thanks.

Edit: I also followed Graasure CORS instructions , but got the same result.

Success. I used rack-cors gem and the following:

 #application.rb config.middleware.use Rack::Cors do allow do origins '*' # location of your API resource '/api/*', :headers => :any, :methods => [:get, :post, :options, :put] end end 
+5
source share
1 answer

You get an Access-Control-Allow-Origin error every time you make a request.

This is probably due to the fact that your server API does not respond to OPTIONS requests with the headers required by CORS.

You can check it on the tab "Development Console →" if you use Google Chrome.

Interestingly, some Javascript frameworks make an OPTIONS request before a regular request is sent to the server.

Decision:

  • Modify your gemfile to enable corsage .
  • Run install package
  • Change your config.ru :

* if you get rails server startup errors, check the API namespace after "run"

 require 'rack/cors' use Rack::Cors do allow do origins '*' resource '*', headers: :any, methods: [:get, :post, :options, :put] end end run API::V1::Base 

You should now see that Grape handles all OPTIONS requests with CORS headers.

+4
source

Source: https://habr.com/ru/post/1207132/


All Articles