我将要拔头发了……从早上开始,我一直在尝试在此Rails应用程序中启用CORS,但这根本行不通。我试过这个,使用 机架一个Cors宝石,这个答案)与此职位均无功而返。
有人可以指出我正确的方向吗?
这是我的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, GET, OPTIONS' headers['Access-Control-Allow-Headers'] = 'X-Requested-With, X-Prototype-Version' headers['Access-Control-Max-Age'] = '1728000' end
您应该使用机架cors
它提供了一个不错的DSL,可用于config/application.rb,而不是凌乱的标头工作以及过滤器之前的工作。
config/application.rb
允许的情况如下,但是,当然,您必须对其进行一些调整。
use Rack::Cors do allow do origins '*' resource '*', headers: :any, methods: :any end end