【发布时间】:2014-06-20 19:47:29
【问题描述】:
我在 heroku 上使用 Rails 4,需要启用 CORS。
我已经在网上浏览了几个小时,并尝试了各种解决方案,这些解决方案对许多其他人都有效,但不适用于我。
我最后一次尝试是简单地将 CORS 添加到应用程序控制器中的所有请求中:
before_filter :cors_preflight_check
after_filter :set_headers
def set_headers
#if request.headers["HTTP_ORIGIN"]
# better way check origin
#if request.headers["HTTP_ORIGIN"] && /^https?:\/\/(.*)\.(.*)\.cloudfront\.net$/i.match(request.headers["HTTP_ORIGIN"])
headers['Access-Control-Allow-Origin'] = '*'
headers['Access-Control-Allow-Methods'] = 'POST, GET, OPTIONS'
headers['Access-Control-Allow-Headers'] = %w{Origin Accept Content-Type X-Requested-With auth_token X-CSRF-Token}.join(',')
headers['Access-Control-Max-Age'] = "1728000"
#end
#end
end
def cors_preflight_check
if request.method == "OPTIONS"
headers['Access-Control-Allow-Origin'] = 'http://localhost'
headers['Access-Control-Allow-Methods'] = 'POST, GET, OPTIONS'
headers['Access-Control-Allow-Headers'] = %w{Origin Accept Content-Type X-Requested-With auth_token X-CSRF-Token}.join(',')
headers['Access-Control-Max-Age'] = '1728000'
render :text => '', :content_type => 'text/plain'
end
end
注释行是为了使所有内容更加干净。但是,这些都不起作用。这就是this thread 告诉我的做法。
你有什么想法或提示我如何让它工作吗?
提前致谢!
【问题讨论】:
-
这是一个很好的问题,需要回答,我自己已经找了几个小时了。
-
我现在就发布我的解决方案
-
我昨晚遇到了这个问题,我很不高兴!
标签: heroku ruby-on-rails-4 cors assets