我正在尝试遵循Ember入门指南并构建一个TodoMVC应用程序,但使用Ember-CLI和Rails作为后端。不幸的是,我遇到了跨站点域名的问题。我收到此错误消息,我尝试发布帖子请求:
XMLHttpRequest cannot load http://localhost:3000/api/todos. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access.
在Rails端我安装了Rack Cors。我已将它添加到我的Gemfile中:
gem 'rack-cors', :require => 'rack/cors'
在我的application.rb
文件中,我有:
module Todoemberrails
class Application < Rails::Application
config.assets.enabled = false
config.middleware.use Rack::Cors do
allow do
origins '*'
resource '*', headers: :any, methods: [:get, :post, :put, :delete, :options]
end
end
end
end
这是我的控制者:
class Api::TodosController < ApplicationController
def index
render json: Todo.all
end
def show
render json: Todo.find(params[:id])
end
def create
todo = Todo.new(todo_params)
if todo.save
render json: todo, status: :created
else
render json: todo.errors, status: :unprocessed
end
end
private
def todo_params
params.require(:todo).permit(:title, :is_completed)
end
end
在我app/adapters/application.js
的{Ember'应用中,我有:
import DS from 'ember-data';
export default DS.RESTAdapter.extend({
host: 'http://localhost:3000/api'
});
答案 0 :(得分:0)
Rails默认不允许这样做,以防止跨站点脚本。
如果你想在整个主板上允许这个,你可以将它添加到你的ApplicationController:
after_filter :cors_set_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'
headers['Access-Control-Allow-Credentials'] = 'true'
end
开始使用Ember指南,,但不适用于制作应用。