Ember-CLI 和 Rails:没有 'Access-Control-Allow-Origin' header 错误

Ember-CLI and Rails: No 'Access-Control-Allow-Origin' header error

我正在尝试使用 Ember-CLI (ember.js) 和 Rails 4.2.0 构建应用程序。我将 Ember 和 Rails 代码库分开,因此我使用 rack-cors gem 启用了 CORS。当 Ember 应用向 Rails api 发出请求时,我不断收到以下错误:

406 Not Acceptable

并且:

No 'Access-Control-Allow-Origin' header is present on the requested 
resource. Origin 'http://localhost:4200' is therefore not allowed access.

Rails 方面:

Processing by CustomersController#index as HTML
Completed 406 Not Acceptable in 2ms

ActionController::UnknownFormat (ActionController::UnknownFormat):
  app/controllers/customers_controller.rb:9:in `index'

请求接受 header 是:

Accept:application/json, text/javascript, */*; q=0.01

我的控制器动作是:

  def index
    @customers = Customer.all

    respond_to do |format|
      format.json { render json: @customers }
      #format.js { render json: @customers } Tried this too
    end
  end

我也有一个 customer_serializer 使用 active_model_serializer gem。

任何帮助将不胜感激!

我在 ember 上使用 rails-csrf 将 X-CSRF-Token 添加到我的所有请求中,rails 默认查找它,因此您只需发送 csrf 令牌至 ember 以完成此工作(rails 侧不需要更多宝石)。 首先你需要安装 rails-csrf npm 包。在您的 ember cli 文件夹中 运行:

npm install rails-csrf --save

然后将初始化器添加到app/app.js文件中:

loadInitializers(App, 'rails-csrf');

然后你将不得不生成一个应用程序路由:

ember generate route application

并添加一个before_model:

export default Ember.Route.extend({
  beforeModel: function() {
    return this.csrf.fetchToken();
  }
});

如果您默认使用 --proxy http://localhost:3000 option then fetchToken will look for your csrf token in http://localhost:3000/api/csrf 启动 ember 服务器。因此,您需要在 rails 端添加路由和控制器。

首先将命名空间路由添加到您的 config/routes.rb 文件

namespace :api do
  get :csrf, to: 'csrf#index'
end

然后在app/controllers/api/csrf_controller.rb

里面添加csrf控制器
class Api::CsrfController < ApplicationController
  def index
    render json: { request_forgery_protection_token => form_authenticity_token }.to_json
  end
end

现在,如果您有 rails 运行ning 并在浏览器中打开 http://localhost:3000/api/csrf url,您应该会看到带有 csrf 令牌的 json 哈希。现在所有 ember 对代理服务器的请求都将在 X-CSRF-Token 中设置 csrf 令牌,默认情况下 rails 会查找。

应该是这样,只需 remember 以确保启动 ember 服务器时将代理设置为 rails 服务器,并且 rails 是还上。

我的客户需要路线 :defaults => { :format => :json }

resources :customers, :defaults => { :format => :json }

这样就可以了!