pcasa
pcasa

Reputation: 3730

rails, rack-cors, nginx, angualrjs and cors

Still getting "Origin MYSITE.com is not allowed by Access-Control-Allow-Origin." errors.

in my controller i have

def subscribe
  gibbon = Gibbon::Request.new
  @list_id = 'some_id'
  begin
    resp = gibbon.lists(@list_id).members.create({body: subscribe_params})
    render json: {}, status: 200
  rescue Gibbon::MailChimpError => e
    render json: e.body, status: e.body['status']
  end
end

in my config/application.rb

config.middleware.insert_before 0, "Rack::Cors", :debug => true, :logger => (-> {Rails.logger }) do
  allow do
    origins(/http:\/\/localhost:(\d*)/,
            /http:\/\/.*\.MYSITE\.com/,
            /http:\/\/MYSITE\.com/,
           )
    resource '*',
      :headers => :any,
      :methods => [:get, :post, :delete, :put, :options, :head, :patch],
      :max_age => 0
  end
end

in my routes.rb I have

namespace :api, defaults: {format: 'json'} do
    scope module: :v1, constraints: ApiConstraints.new(version: 1, default: :true) do
      resources :mailers do
        collection do
          post :subscribe
          get :members
        end
      end
      match '*path', via: [:options], to:  lambda {|_| [204, {'Content-Type' => 'text/plain'}, []]}
    end
  end

in my nginx > sites-enabled > MYSITE.con

try_files $uri/index.html $uri @unicorn;
  location @unicorn {
    add_header 'Access-Control-Allow-Origin' '*';

    add_header X-Forwarded-For $proxy_add_x_forwarded_for;
    add_header Host $http_host;
    proxy_redirect off;
    proxy_pass http://unicorn;
  }

Upvotes: 0

Views: 639

Answers (1)

pcasa
pcasa

Reputation: 3730

For others going through a similar problem, the issue was with the nginx conf.

Needed to remove add_header 'Access-Control-Allow-Origin' '*';

At first did not notice that Access-Control-Allow-Origin response headers where coming back as http://MYSITE, * which is invalid. Only 1 origin is allowed.

Upvotes: 2

Related Questions