Rails Access-Control-Allow-Origin 怎么设置

279959599 · March 28, 2015 · Last by ericguo replied at August 09, 2015 · 9917 hits

我的网站在做第三方登录功能,需要有 post 方式跨站请求,但是提示我这个错我 No 'Access-Control-Allow-Origin' header is present on the requested resource 貌似需要设置这个,怎么设置呢,有人说用 jsonp 方式提交,但是 jquery 和 js 都不支持 post 方式的请求

gem 'rack-cors'

也就是说前端无法实现跨域 post 请求吧

如下操作,可以设置该头部,不过大都使用 gem 来实现。

$.ajax({
    url: 'foo/bar',
    method: 'POST',
    data: {message: 'next'},
    headers: { ''Access-Control-Allow-Origin'': '*' }
});

gem 'rack-cors'


#congfig.ru
require 'rack/cors'
use Rack::Cors do
  allow do
    origins '*'
    resource '*',
      headers: :any,
      methods: [:get, :post, :put, :delete, :options]
  end
end

手动设置也行:

app/controllers/application_controller.rb

after_action :access_control_headers

def access_control_headers
  headers['Access-Control-Allow-Origin'] = "*" # or your web site like http://localhost:4200
  headers['Access-Control-Request-Method'] = %w{GET POST OPTIONS}.join(",")
end
You need to Sign in before reply, if you don't have an account, please Sign up first.