Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CORS issue using Grape API and Heroku

I have a read-only API and it works well locally with a Vagrant setup. Live on my Heroku app, every API request is denied due to a CORS error: "No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access."

In my API's base 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 is not being fired—if I use a puts statement inside of it, that statement does not appear in my console with the rest of the output.

I am at a loss. Hopefully someone has some experience with this. Thank you.

Edit: I have also followed Grape's CORS instructions but get the same result.

Success. I used the 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
like image 214
Stephen Avatar asked Nov 18 '14 15:11

Stephen


1 Answers

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

This is probably because your server API does not respond to OPTIONS requests with the headers required for CORS.

You can check it in the development console -> network tab if you are using Google Chrome.

It's interesting that some Javascript frameworks do make an OPTIONS request before a normal request is sent to the server.

Solution:

  1. Modify your Gemfile to include 'rack-cors'.
  2. Run bundle install
  3. Modify your config.ru:

*if you get errors launching rails server, check your 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

Now you should see Grape handles all OPTIONS requests with the CORS headers.

like image 143
Ryanzyy Avatar answered Sep 24 '22 12:09

Ryanzyy