如何在Rails 4 App中启用CORS [英] How to enable CORS in Rails 4 App

查看:121
本文介绍了如何在Rails 4 App中启用CORS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正要拔头发...从早上开始,我一直在尝试在此Rails应用程序中启用CORS,但这只是无效。我已经尝试使用: //github.com/cyu/rack-cors rel = noreferrer>机架Cors宝石,此答案和此帖子均未成功。

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();
        }

当我尝试此URL(来自外部客户端)时:可以正常工作的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


推荐答案

使用机架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 App中启用CORS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆