ruby-on-rails – 如何在Rails 4应用程序中启用CORS

我只是把我的头发拉出来…我早就试图在这个Rails应用程序中启用CORS,而且它不起作用.我试过 this,使用 Rack Cors Gem,this answer和这 post都没有成功.

有人可以指向正确的方向吗?

这是我的js:

var req = new XMLHttpRequest();

      if ('withCredentials' in req) {
            // req.open('GET',"https://api.github.com/users/mralexgray/repos",true);
            req.open('GET',"http://www.postcoder.lc/postcodes/" + value,true);
            // Just like regular ol' XHR
            req.onreadystatechange = function() {
                if (req.readyState === 4) {
                    if (req.status >= 200 && req.status < 400) {
                        // JSON.parse(req.responseText) etc.
                        console.log(req.responseText);
                    } else {
                        // Handle error case
                    }
                }
            };
            req.send();
        }

当我尝试这个url(从外部客户端):https://api.github.com/users/mralexgray/repos这可以正常工作,我假设问题是与我的Rails API.我错了吗?

编辑:目前我在控制器里有这个:

skip_before_filter :verify_authenticity_token
before_filter :cors_preflight_check
after_filter :cors_set_access_control_headers

# For all responses in this controller,return the CORS access control headers.
def cors_set_access_control_headers
  headers['Access-Control-Allow-Origin'] = '*'
  headers['Access-Control-Allow-Methods'] = 'POST,GET,OPTIONS'
  headers['Access-Control-Max-Age'] = "1728000"
end

# If this is a preflight OPTIONS request,then short-circuit the
# request,return only the necessary headers and return an empty
# text/plain.

def cors_preflight_check
  headers['Access-Control-Allow-Origin'] = '*'
  headers['Access-Control-Allow-Methods'] = 'POST,OPTIONS'
  headers['Access-Control-Allow-Headers'] = 'X-Requested-With,X-Prototype-Version'
  headers['Access-Control-Max-Age'] = '1728000'
end

解决方法

你应该使用 rack cors

它提供了一个不错的DSL,在你的config / application.rb中使用,而不是凌乱的标题工作和过滤器之前.

一个非常宽容的将如下,但当然,你必须定制一下.

use Rack::Cors do
  allow do
    origins '*'
    resource '*',headers: :any,methods: :any
  end  
end

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...