PhoneGap Angular app和Rails的CORS问题

时间:2014-08-17 02:22:54

标签: angularjs cordova ruby-on-rails-4

开始使用PhoneGap,使用Yeoman,bower和grunt设置Angular。我试图从我的Rails API获得响应并始终获得XMLHttpRequest cannot load http://localhost:3000/api/v1/sessions. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:9000' is therefore not allowed access.

我已经尝试了本书中的每个解决方案,但无法实现这一点。

这是必要的代码:

class Api::V1::BaseController < ActionController::Base
  respond_to :json

  protect_from_forgery with: :null_session

  before_filter :set_cors_headers
  before_filter :cors_preflight

  def set_cors_headers
    headers['Access-Control-Allow-Origin'] = AppConfig.client['origin']
    headers['Access-Control-Allow-Methods'] = 'GET, POST, PUT, DELETE, OPTIONS'
    headers['Access-Control-Allow-Headers'] = '*'
    headers['Access-Control-Max-Age'] = "3628800"
  end

  def cors_preflight
    head(:ok) if request.method == :options
  end
end

在我的app_config.yml文件中:

defaults: &defaults
  client:
    origin: http://localhost:9000

development:
  <<: *defaults

test:
  <<: *defaults

production:
  <<: *defaults

我在初始化程序app_config.rb中加载它:

require 'ostruct'
require 'yaml'

config = YAML.load_file(File.join(Rails.root, 'config', 'app_config.yml')) || {}
AppConfig = OpenStruct.new(config[Rails.env] || {})

我也尝试使用Rack CORS gem,并在我的application.rb中使用它:

module MyApp
  class Application < Rails::Application
    config.middleware.use Rack::Cors do
      allow do
        origins '*'
        resource '*', :headers => :any, :methods => [:get, :post, :options, :delete]
      end
    end
  end
end

使用Rails 4.1。

2 个答案:

答案 0 :(得分:0)

要在Angular中使用CORS,我们需要告诉Angular我们正在使用CORS。我们使用.config() 我们的Angular app模块上的方法设置了两个选项。 首先,我们需要告诉Angular使用XDomain,我们必须删除X-Requested-With标头 来自我们的所有要求。

angular.module('myApp')
   .config(function($httpProvider) {
     $httpProvider.defaults.useXDomain = true;
       delete $httpProvider.defaults.headers
        .common['X-Requested-With'];
});

现在我们已准备好发出CORS请求了。

答案 1 :(得分:0)

不确定您是否能够解决此问题,但PhoneGap应将所有域列入白名单 - 请检查您的config.xml ...现在,如果您使用的是“Live Reload”服务器(如Ionic) / Steroids / etc),似乎存在一个问题,即实时重新加载服务器以在运行时删除*的白名单的方式修改config.xml ...

如果这仍然让您感到痛苦,请查看此主题以获取更多详细信息 - https://github.com/driftyco/ionic-cli/issues/89

在整个帖子中,你会看到多个解决方法..对我来说,只修改我的开发服务器的CORS已经证明最简单 - 因为这不应该是生产问题,因为不会使用实时重新加载,因此配置中的白名单.xml应解决任何CORS问题。