首页 文章

铁轨,机架,nginx,angualrjs和cors

提问于
浏览
0

Access-Control-Allow-Origin不允许“Origin MYSITE.com” . 错误 .

在我的控制器中我有

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

在我的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

在我的routes.rb我有

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

在我的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;
  }

1 回答

  • 1

    对于遇到类似问题的其他人来说,问题在于nginx conf .

    需要删除 add_header 'Access-Control-Allow-Origin' '*';

    起初没有注意到 Access-Control-Allow-Origin 响应头回到 http://MYSITE, * 这是无效的 . 只允许1个来源 .

相关问题