如何在 Rails 4 应用程序中启用 CORS

How to enable CORS in Rails 4 App(如何在 Rails 4 应用程序中启用 CORS)
本文介绍了如何在 Rails 4 应用程序中启用 CORS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我正要拔掉头发...从早上开始,我一直在尝试在这个 Rails 应用程序中启用 CORS,但它不起作用.我试过 this,使用 Rack Cors Gem, 这个答案和这个post都没有成功.

I'm just about to pull my hair out... I've been trying to enable CORS in this Rails app since the morning and it just doesn't work. I've tried this, using Rack Cors Gem, this answer and this post all without success.

有人能指出正确的方向吗?

Can someone point me in the right direction?

这是我的 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();
        }

当我尝试这个网址时(来自外部客户端):https://api.github.com/users/mralexgray/repos 工作正常,我假设问题出在我的 Rails API 上.我错了吗?

When I try this url (from an external client): https://api.github.com/users/mralexgray/repos that works ok, I'm assuming the problem is with my Rails API. Am I wrong?

目前我的控制器中有这个:

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

推荐答案

你应该使用 rack cors

它提供了一个很好的 DSL,可以在你的 config/application.rb 中使用,而不是在过滤器之前使用凌乱的标题.

It provides a nice DSL, to use in your config/application.rb, instead of the messy header work and before filters.

一个非常宽松的方法如下,但当然,你必须稍微调整一下.

A very permissive would be as follows, but of course, you'll have to tailor it a bit.

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

这篇关于如何在 Rails 4 应用程序中启用 CORS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

Show a progress bar for downloading files using XHR2/AJAX(显示使用 XHR2/AJAX 下载文件的进度条)
How do I get the HTTP status code with jQuery?(如何使用 jQuery 获取 HTTP 状态码?)
How to get response url in XMLHttpRequest?(如何在 XMLHttpRequest 中获取响应 url?)
WebKit quot;Refused to set unsafe header #39;content-length#39;quot;(WebKit “拒绝设置不安全的标头‘内容长度’)
$.ajax call working fine in IE8 and Doesn#39;t work in firefox and chrome browsers($.ajax 调用在 IE8 中运行良好,但在 Firefox 和 chrome 浏览器中不起作用)
How do I know if jQuery has an Ajax request pending?(我如何知道 jQuery 是否有待处理的 Ajax 请求?)